在Python中将一个文件的奇数行复制到另一个文件

Let suppose there is a file named "file1.txt", that contains following content,

假设有一个名为“ file1.txt ”的文件,其中包含以下内容,

    This is line 1.
    This is line 2.
    This is line 3.
    This is line 4.
    This is line 5.

And, we are copying odd lines to another file named "file2.txt".

并且,我们正在将奇数行复制到另一个名为“ file2.txt ”的文件。

Example:

例:

    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程序将一个文件的奇数行复制到另一个文件 (Python program to copy odd lines of one file to another file)

# opening the file
file1 = open('file1.txt', 'r') 

# creating another file to store odd lines
file2 = open('file2.txt', 'w') 

# reading content of the files
# and writing odd lines to another file
lines = file1.readlines() 
type(lines) 
for i in range(0, len(lines)): 
	if(i % 2 != 0): 
		file2.write(lines[i]) 

# closing the files
file1.close()
file2.close() 

# opening the files and printing their content
file1 = open('file1.txt', 'r') 
file2 = open('file2.txt', 'r') 

# reading and printing the files content
str1 = file1.read()
str2 = file2.read()

print("file1 content...")
print(str1)

print() # to print new line

print("file2 content...")
print(str2)

# closing the files
file1.close()
file2.close()

Output

输出量

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.


翻译自: https://www.includehelp.com/python/copy-odd-lines-of-one-file-to-another-file-in-python.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值