python - 将行复制到 python 中

标签 python file python-3.x

我正在尝试编写一个程序,将 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/

相关文章:

Python:使用 type() 时缺少类属性 __module__?

Java .split() 越界

java - Android 无法从文件路径获取缓存图像

python-3.x - 有人可以帮我解决我的 python 代码中的错误吗?

python - 如何使用算术符号而不是内置函数

python - 需要帮助将 python 代码(使用 Numpy)翻译成 Matlab 等价物

python - 在 Python 中重新格式化制表符分隔的数据

android - 是否可以在任何设备和平台上启动 android 中的 native 文件管理器?

python - python的温度转换

python - 如何获取字典元组的最大值