gpt4 book ai didi

python - 使用 Python 替换文件中的单词的问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:48:00 24 4
gpt4 key购买 nike

我有一个包含如下数据的 .txt 文件:

1,Rent1,Expense,16/02/2010,1,4000,4000  
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,4000,8000

我想替换第一项。如果它是 1,意味着它应该保持不变,但如果它是 0 意味着我想将它更改为 1。所以我尝试使用以下代码:

import fileinput
for line in fileinput.FileInput("sample.txt",inplace=1):
s=line.split(",")
print a
print ','.join(s)

但在成功执行程序后,我的 .txt 文件如下所示:

1,Rent1,Expense,16/02/2010,1,4000,4000

1,Car Loan1,Expense,16/02/2010,2,4500,9000

1,Flat Loan1,Expense,16/02/2010,2,4000,8000

0,Rent2,Expense,16/02/2010,1,4000,4000

0,Car Loan2,Expense,16/02/2010,2,4500,9000

0,Flat Loan2,Expense,16/02/2010,2,4000,8000

现在我想删除空行。是否可以,或者是否有任何其他方法来替换 0?

最佳答案

print 在输入后添加了一个额外的换行符,而您那里已经有了一个换行符。您应该删除现有的换行符 (line.rstrip("\n")) 或改用 sys.stdout.write()

关于python - 使用 Python 替换文件中的单词的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2271199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com