tags:

views:

123

answers:

4

Hi,

I am new to Python programming...

I have a .txt file....... It looks like..

0,Salary,14000

0,Bonus,5000

0,gift,6000

I want to to replace the first '0' value to '1' in each line. How can I do this? Any one can help me.... With sample code..

Thanks in advance. Nimmyliji

+2  A: 
f = open(filepath,'r')
data = f.readlines()
f.close()

edited = []
for line in data:
    edited.append( '1'+line[1:] )

f = open(filepath,'w')
f.writelines(edited)
f.flush()
f.close()

Or in Python 2.5+:

with open(filepath,'r') as f:
   data = f.readlines()

with open(outfilepath, 'w') as f:
   for line in data:
      f.write( '1' + line[1:] )

This should do it. I wouldn't recommend it for a truly big file though ;-) What is going on (ex 1):

1: Open the file in read mode

2,3: Read all the lines into a list (each line is a separate index) and close the file.

4,5,6: Iterate over the list constructing a new list where each line has the first character replaced by a 1. The line[1:] slices the string from index 1 onward. We concatenate the 1 with the truncated list.

7,8,9: Reopen the file in write mode, write the list to the file (overwrite), flush the buffer, and close the file handle.

In Ex. 2:

I use the with statement that lets the file handle closing itself, but do essentially the same thing.

SapphireSun
`rw` is invalid, and even if it wasn't, writing would begin at the end of the file.
Ignacio Vazquez-Abrams
Oh snap, I'll fix that (I could have sworn that append was a '+').
SapphireSun
It seems 'rw' mode is not totally invalid. You can read the file, but if you try to write you get an IOError (even if you try writing before you read).
SapphireSun
I guess, `flush()` is redundant as you close file anyway.
Rorick
A: 
o=open("output.txt","w")
for line in open("file"):
    s=line.split(",")
    s[0]="1"
    o.write(','.join(s))
o.close()

Or you can use fileinput with in place edit

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    s=line.split(",")
    s[0]="1"
    print ','.join(s)
ghostdog74
`a` will preserve what was already in the file.
Ignacio Vazquez-Abrams
+4  A: 

I know that you're asking about Python, but forgive me for suggesting that perhaps a different tool is better for the job. :) It's a one-liner via sed:

sed 's/^0,/1,/' yourtextfile.txt > output.txt

This applies the regex /^0,/ (which matches any 0, that occurs at the beginning of a line) to each line and replaces the matched text with 1, instead. The output is directed into the file output.txt specified.

Amber
what he wants to do may be part of a bigger task. "Better for the job" maybe not.
ghostdog74
The regular expression can be implemented using the Python regex module. So while `sed` may not be a good answer, the concept of a regex is, IMHO.
Matthew Iselin
+3  A: 
inFile = open("old.txt", "r")
outFile = open("new.txt", "w")
for line in inFile: 
    outFile.write(",".join(["1"] + (line.split(","))[1:]))

inFile.close()
outFile.close()

If you would like something more general, take a look to Python csv module. It contains utilities for processing comma-separated values (abbreviated as csv) in files. But it can work with arbitrary delimiter, not only comma. So as you sample is obviously a csv file, you can use it as follows:

import csv
reader = csv.reader(open("old.txt"))
writer = csv.writer(open("new.txt", "w"))
writer.writerows(["1"] + line[1:] for line in reader)

To overwrite original file with new one:

import os
os.remove("old.txt")
os.rename("new.txt", "old.txt")

I think that writing to new file and then renaming it is more fault-tolerant and less likely corrupt your data than direct overwriting of source file. Imagine, that your program raised an exception while source file was already read to memory and reopened for writing. So you would lose original data and your new data wouldn't be saved because of program crash. In my case, I only lose new data while preserving original.

Rorick
+1 for mentioning the csv module. It has really saved my bacon *so* many times!
Daren Thomas