0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Do you want to replace the newlines as well?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.