我正在尝试编写一个程序,将 thisFile.txt
中的每隔一行复制到 thatFile.txt
中,但现在,我无法获取将 thisFile.txt
中的行复制到 thatFile.txt
中。
我尝试使用两种不同的方法来复制,一种是注释掉的方法,另一种是在注释部分之前的 for 循环中。
file_one=open('thisFile.txt','w+')
file_two=open('thatFile.txt','w+')
file_one.write('Hello\nHow\nAre\nYou')
for line in file_one:
file_two.write(line)
#line=' '
#while line !='':
# line=file_one.readline()
# file_two.write(line)
file_one.close()
file_two.close()
最佳答案
您已打开两个文件进行读取和写入,但写入第一个文件后希望立即从该文件中读取。文件指针位于文件末尾。如果您 .seek(0)
返回到文件的开头,它将起作用:
file_one=open('thisFile.txt','w+')
file_two=open('thatFile.txt','w+')
file_one.write('Hello\nHow\nAre\nYou')
# rewind the file to prep for read.
file_one.seek(0)
for line in file_one:
file_two.write(line)
file_one.close()
file_two.close()
关于python - 将行复制到 python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33272611/