views:

188

answers:

8

I have a .txt file containing data like this:

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 

I want to replace the first item. If it is 1, means it should remain the same but if it is 0 means I want to change it to 1. So I have tried using the following code:

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

But after successfully executed the program my .txt file looks like:

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

Now I want to remove the empty line. Is it possible, or is there any other way to replace the 0's?

+1  A: 

Either use rstrip to remove the trailing new lines before printing or use sys.stdout.write instead of print.

Also, if you only need to modify the first element, there is no need to split the entire line and join it again. You only need to split on the first comma:

line.split(',', 1)

If you want even better performance you could also just test the value of line[0] directly.

Mark Byers
+4  A: 

print adds an extra newline after the input and you already have one newline there. You should either strip the existing newline (line.rstrip("\n")) or use sys.stdout.write() instead.

Lukáš Lalinský
+2  A: 
import fileinput
import re
p = re.compile(r'^0,')
for line in fileinput.FileInput("sample.txt",inplace=1):
    print p.sub('1,', line.strip())

The existing code you have doesn't actually change the lines like you want; print a doesn't do anything if a isn't actually defined! So you end up just printing a blank line (the print a bit) and then printing the existing line, hence why you get a file that's unaltered except for the addition of some blank lines.

Amber
+1: just replace `print re.sub(r'^0,', '1,', line)` with `print re.sub(r'^0,', '1,', line.strip())`, which will get rid of empty lines.
van
No need for the strip in the first place; just run it on the original file instead of the blank-lined one.
Amber
with Python26 on Win32 if you do not strip() or rstrip(), you get blank lines on the original file
van
Ah, right, good point.
Amber
A: 
fixed = []
for l in file('sample.txt'):
    parts = l.split(',',1)
    if(parts[0] == '0'):
        # not sure what you want to do here, but you want to "change this" number to 1?
        parts[0] = 1
    fixed.append(parts.join(','))
outp = file('sample.txt','w')
for f in fixed:
    outp.write(f)
outp.close()

This is untested, but it should get you most of the way there. Good luck

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

You have to use a comma at the end of your print so that it doesn't add a newline. Like so:

print "Hello",

This is what I came up with:

input = open('file.txt', 'r')
output = open('output.txt', 'w')
for line in input:
    values = line.split(',')
    if (values[0] == '0'):
        values[0] = '1'
    output.write(','.join(values))

If you want a better csv handling library you might want to use this instead of split.

Richard Nienaber
A: 

Thanks a lot.......

Nimmy
Please mark the answer that has been most helpful to you by clicking on the checkmark icon next to it.
badp
A: 

The cleanest way to do it is to use the CSV parser :

import fileinput
import csv 

f = fileinput.FileInput("test.txt",inplace=1)
fichiercsv = csv.reader(f, delimiter=',')

for line in fichiercsv:
    line[0] = "1"
    print ",".join(line)
e-satis