views:

101

answers:

4

Hi,

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,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 

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? Any one can help me? Plz..........

Thanks in advance, Nimmy

A: 

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
Ignacio Vazquez-Abrams
A: 

Replace:

result = newline #you lose the newline here

with:

result = newline + '\n' #or '\r\n' depending on your newline format.
badp
Thanks a lot...
Nimmy
+2  A: 

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"
ghostdog74
Thanks a lot...
Nimmy
Also, `lnum=='4'` should be `lnum == 4`. Python is strongly typed.
Max Shawabkeh
yes, good catch
ghostdog74
+1  A: 

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)
remosu