ShanZhengYang
ShanZhengYang

Reputation: 17631

Format text file with python script

I have a text file which is formatted with tabs everywhere. Here is what the text file looks like now:

        "item1", 
        "item2", 
        "item3", 
        "item4", 
        "item5", 
        "item6", 
        "item7", 
        "item8",
        ....

In fact, the text file should look like this:

"item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", ....

So, I'm guessing there are extra tabs \t everywhere in the original file.

Is it possible to reformat this list somehow with (let's say) a Python script? How would one do this?

Upvotes: 0

Views: 5417

Answers (2)

Skycc
Skycc

Reputation: 3555

reading the file, use str.strip to strip of the line and write to new file at the same time.

strip will strip of tab or space or newline from both left and right side of the line

with open('input.txt', 'r') as f, open('output.txt', 'w') as fo:
    for line in f:
        fo.write(line.strip())
        # fo.write(line.strip() + '\n') # use this if wanna retain new line

Upvotes: 1

DYZ
DYZ

Reputation: 57033

If the file is not ridiculously large, read it as a string, remove tabs from the string, and write it back:

with open(file_name) as infile:
  replaced = infile.read().replace("\t","")
with open(another_file, "w") as outfile:
  outfile.write(replaced)

If the file is large, read and write it line by line with .readline() and .write() (assuming it has line breaks). If it has no line breaks, read and write it in a loop N characters at a time with .read(N) and .write(). In both cases, replace all tabs with empty strings before writing.

Upvotes: 1

Related Questions