我有一个包含以下数据的.txt文件:
0,Rent1,Expense,16/02/2010,1,4000,4000
0,Car Loan1,Expense,16/02/2010,2,4500,9000
0,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
现在我想用新项目替换第4行:
0,贷款,费用,19/02 / 2010,2,5000,10000
我使用以下代码:
newline='0,Loan,Expense,19/02/2010,2,5000,10000'
lnum=1
for line in fileinput.FileInput("sample.txt",inplace=1):
if lnum=='4':
result = newline
lnum=lnum+1
else:
result=line
lnum=lnum+1
sys.stdout.write(result)
但它显示的文件如下:
0,Rent1,Expense,16/02/2010,1,4000,4000
0,Car Loan1,Expense,16/02/2010,2,4500,9000
0,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Loan,Expense,19/02/2010,2,5000,100000,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,4000,8000
我该如何解决这个问题?
答案 0 :(得分:2)
添加新行
newline='0,Loan,Expense,19/02/2010,2,5000,10000'
lnum=1
for line in fileinput.FileInput("sample.txt",inplace=1):
if lnum==4:
result = newline+"\n"
else:
result=line
lnum=lnum+1
sys.stdout.write(result)
或者您可以将newline
变量声明为
newline="0,Loan,Expense,19/02/2010,2,5000,10000\n"
答案 1 :(得分:1)
使用枚举:减少代码减少错误的可能性
newline = '0,Loan,Expense,19/02/2010,2,5000,10000\n'
for lnum, line in enumerate(fileinput.FileInput("sample.txt",inplace=1)):
if lnum == 4:
line = newline
sys.stdout.write(line)
答案 2 :(得分:0)
sys.stdout.write()
不会添加换行符。添加\n
,之后使用print
或使用print
的文件语法:
print >>sys.stdout, result
...或者因为sys.stdout
是默认值:
print result
答案 3 :(得分:0)
替换:
result = newline #you lose the newline here
使用:
result = newline + '\n' #or '\r\n' depending on your newline format.