简体   繁体   中英

python read from file write to other file

file1 = open('/path/to/file1.txt', "r")
file2 = open('/path/to/file2.txt', "wa")
counter = 1

for line in file1:
    new_string = str(counter) + '\t' + line
    file2.write(new_string)
    counter += 1

I am trying to add a number to the beginning of every line in a file and append this line by line to a new file. There are 1189 lines of text in the original file and despite a number of attempts I only get 1168 lines in the new file. What's going on?

I added a print statement ( print str(counter) + " " + line), all the lines from the original file get printed out with the expected number beside them. The counter variable is 1190 after the loop runs.

EDIT: inserting file2.close() after the loop worked, all 1189 lines are in the second file now, but why?

您是否关闭正在写入的文件,即在循环后执行file2.close()

您的file1file2指向您提供的代码示例中的相同文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM