Skip to main content
 首页 » 编程设计

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

2025年05月04日15jyk

我有一个包含如下数据的 .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()。