在Python中将一个文件的奇数行复制到另一个文件
假设有一个名为“file1.txt”的文件,其中包含以下内容,
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.并且,我们正在将奇数行复制到另一个名为“file2.txt”的文件。
示例
Input: "file1.txt"
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
Output: "file2.txt"
This is line 2.
This is line 4.Python程序将一个文件的奇数行复制到另一个文件
#打开文件
file1 = open('file1.txt', 'r')
#创建另一个文件以存储奇数行
file2 = open('file2.txt', 'w')
#读取文件内容
#并将奇数行写入另一个文件
lines = file1.readlines() type(lines) for i in range(0, len(lines)):
if(i % 2 != 0):
file2.write(lines[i])
#关闭文件
file1.close()file2.close() #打开文件s and printing their content
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')
#读取和打印文件内容
str1 = file1.read()str2 = file2.read()print("file1 content...")
print(str1)print() #打印新行
print("file2 content...")
print(str2)
#关闭文件
file1.close()file2.close()输出结果
file1 content... This is line 1. This is line 2. This is line 3. This is line 4. This is line 5. file2 content... This is line 2. This is line 4.
热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短