开发者

Replace a whole line in a file

I have a .txt file containing data like this:

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,400开发者_JAVA百科0,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 

Now i want to replace the line 4 with the new items like:

0,Loan,Expense,19/02/2010,2,5000,10000

I use the following code:

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)

But it shows the in file like:

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 

How can I solve this?


Put a new line

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)

Or you can just declare newline variable as

newline="0,Loan,Expense,19/02/2010,2,5000,10000\n"


Use enumerate: less code less error posibilities

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)


Replace:

result = newline #you lose the newline here

with:

result = newline + '\n' #or '\r\n' depending on your newline format.


sys.stdout.write() does not add a newline. Either append a \n, use print after, or use print's file syntax:

print >>sys.stdout, result

... Or since sys.stdout is the default:

print result
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜