0

I have 500 text files in one folder, each of them looks like this:

1-1,2-4,In,_,
1-2,5-9,this,_,
1-3,10-15,paper,_,
1-4,16-18,we,_,
1-5,19-26,propose,_,
1-6,27-28,a,Project[1],

I need to add one word at the end of the text in each of the files. The result I expect is:

1-1,2-4,In,_,
1-2,5-9,this,_,
1-3,10-15,paper,_,
1-4,16-18,we,_,
1-5,19-26,propose,_,
1-6,27-28,a,Project[1],
end

How do I write inside the with block?

import os

path = "All_TSV_Files"
files = [file for file in os.listdir(path) if file.endswith(".txt")]
for file in files:
    with open(os.path.join(path, file), 'r',encoding='utf-8') as f:
        ### add "end" to end of the file

or should I use pandas data frame to do them?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Eric
  • 1
  • 1
  • Also useful [Difference between modes a, a+, w, w+, and r+ in built-in open function?](https://stackoverflow.com/q/1466000/15497888) – Henry Ecker Aug 31 '21 at 23:02

2 Answers2

1

Say your file is called "foo.txt", you can open it with intend of appending to it like this:

with open("foo.txt", "a") as f:
    f.write("\nend")

The \n denotes a newline before inserting end.

0

This answer should be helpful: Write to the last line of a text file?

Just open file in append mode (pointer will be in the ned of file) and write line.

poleszcz
  • 145
  • 9