简体   繁体   English

python从文件读取写入其他文件

[英]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. 原始文件中有1189行文本,尽管进行了多次尝试,但新文件中却只有1168行。 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. 我添加了一条打印语句(print str(counter)+“” +行),原始文件中的所有行都被打印出来,并带有期望的数字。 The counter variable is 1190 after the loop runs. 循环运行后,计数器变量为1190。

EDIT: inserting file2.close() after the loop worked, all 1189 lines are in the second file now, but why? 编辑:循环工作后插入file2.close(),所有1189行现在在第二个文件中,但是为什么呢?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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