Open a file with open inside a with block. The block closes the file when
it ends, including when an error is raised.
with open("counts.tsv") as handle:
first_line = handle.readline()
print(first_line.strip())
The sandbox has several files mounted already. counts.tsv and variants.tsv
are used in the examples below.
Reading line by line
Looping over the handle reads one line at a time, which works on files too large to fit in memory.
with open("variants.tsv") as handle:
for line in handle:
print(line.strip())
Each line keeps its trailing newline, so strip() is almost always needed.
Reading it all at once
with open("counts.tsv") as handle:
text = handle.read()
print(len(text), "characters")
with open("counts.tsv") as handle:
lines = handle.read().splitlines()
print(len(lines), "lines")
Splitting columns
A tab-separated line splits on \t.
with open("counts.tsv") as handle:
header = handle.readline().strip().split("\t")
print(header)
for line in handle:
fields = line.strip().split("\t")
print(fields[0], fields[1])
Writing
"w" creates or overwrites. "a" appends.
with open("output.txt", "w") as handle:
handle.write("gene\tdepth\n")
handle.write("TP53\t120\n")
with open("output.txt") as handle:
print(handle.read())
Task
Write column_sum(path, column). Read a tab-separated file with a header row,
and return the sum of the named column as an integer. Assume the column exists
and every value in it is a whole number.
Test cases · 2
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | control_1 | 20910 |
| 2 | stdin | treated_2 | 22306 |
Hints · 2
01Hint
Read the header first, then use header.index(column) to find the position.
02Hint
Skip blank lines before splitting, or the split will produce an empty field.