将行复制到python中
我正试图编写一个程序,每隔一行从将行复制到python中,python,file,python-3.x,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 i
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()
解决第一个问题(复制所有行)。您需要在
mode='r'
中打开所需的文件,然后写入下一个文件,该文件是使用mode='w'
打开的(或者只需'r'
和'w'
)
对于第一个文件,您使用readlines()
实际读取每一行
要解决第二个问题(每隔一行):
您只需要实现
enumerate()
来循环遍历列表,并只提供键为偶数的行。当然,您可以更改为奇数。您已打开两个文件进行读写,但在写入第一个文件后,您希望立即从该文件读取。文件指针位于文件的末尾。如果.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()
with open('test.txt', 'r') as f1:
lines = f1.readlines()
with open('test2.txt', 'w') as f2:
for i,line in enumerate(lines):
if i % 2 == 0:
f2.write(line)
else:
pass
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()