moth
moth

Reputation: 2389

Is it possible to read and write the same file when iterating lines?

I am trying to enforce that a file is tabulated in python and I would like to read and write the file at the same time, perhaps it's not possible because the pointer has already moved away when trying to write.

Consider the file.txt

chr1 557044 557064 FUS 1000 +
chr1 870106 870128 FUS 1000 +
chr1 936672 936706 FUS 1000 +
chr1 1433046 1433067 FUS 1000 +

I am running the following code to make this file tab delimited:

with open(file="file.txt",mode='r+') as file:
    for line in file:
        file.write('\t'.join(line.strip().split() + '\n'))

But I get the following error:

TypeError: can only concatenate list (not "str") to list

Upvotes: 0

Views: 126

Answers (3)

not_speshal
not_speshal

Reputation: 23156

To deal with extra spaces between words, strip() each word in the line before you join() with tabs. As an aside, collect all the text you want to write into a variable (contents in the below code) and write it after the required formatting.

Try this:

contents = ""
with open("file.txt", "r+") as f:
    for line in f:
        contents += "\t".join(word.strip() for word in line.split()) + "\n"

with open("file.txt", "w") as f:
    f.write(contents)

Upvotes: 1

Kunal Sharma
Kunal Sharma

Reputation: 426

you are getting error because split return a list and you are trying to add str with list you can get you task done by:

with open(file="file.txt",mode='r+') as file:
    file.write(file.read().replace(" ", "\t"))

Upvotes: 0

Shirayuki
Shirayuki

Reputation: 189

You are getting the errors because you are trying to add a list and a string together. .split() will create a list, and adding a '\n' to that list is the reason why it errored out

Upvotes: 2

Related Questions