473,386 Members | 1,786 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

replace string in a file

Hi,
I've got this code :

cb = open("testfile", "r+")
f = cb.readlines()
for line in f:
rx = re.match(r'^\s*(\d+).*', line)
if not rx:
continue
else:
serial = rx.group(1)
now = time.time()
today = time.strftime('%Y%m%d00', time.localtime(now))
todayVal, serialVal = long(today), long(serial)
if todayVal <= serialVal:
todayVal = serialVal + 1
else:
todayVal += 1
line = string.replace(line, serial, "%d" %todayVal)
cb.write(line + "\n")
print 'Updated serial from "%s" to "%d"' % ( serial, todayVal )
break
cb.close()

I was expecting to replace the old value (serial) with the new one
(todayVal). Instead, this code *adds* another line below the one found...

How can I just replace it?

Thanks for your help :-)
Mar 15 '08 #1
5 2561
On Mar 15, 3:54*pm, Unknown <cantabile...@wanadoo.frwrote:
Hi,
I've got this code :

cb = open("testfile", "r+")
f = cb.readlines()
for line in f:
* * rx = re.match(r'^\s*(\d+).*', line)
* * if not rx:
* * * * continue
* * else:
* * * * serial = rx.group(1)
* * * * now = time.time()
* * * * today = time.strftime('%Y%m%d00', time.localtime(now))
* * * * todayVal, serialVal = long(today), long(serial)
* * * * if todayVal <= serialVal:
* * * * * * todayVal = serialVal + 1
* * * * else:
* * * * * * todayVal += 1
* * * * line = string.replace(line, serial, "%d" %todayVal)
* * * * cb.write(line + "\n")
* * * * print 'Updated serial from "%s" to "%d"' % ( serial, todayVal )
* * * * break * * *
cb.close()

I was expecting to replace the old value (serial) with the new one
(todayVal). Instead, this code *adds* another line below the one found...

How can I just replace it?

Thanks for your help :-)
What you want to do is either 1. load everything up into a string,
replace
text, close file, reopen it with 'w' flag, write string to it. OR if
file is too big, you can read each line, replace, write to a temp
file,
then when done move the file over the old one.

I think there are technical reasons why file-reading and iteration api
are not very suitable for reading and writing at the same time. I
think
you'd have to set the filepointer back one line (it can be manipulated
by giving it bytes ahead/back, so that would be difficult in itself),
then delete the line and then write new string. It may be even harder
than
that, I'm sure someone can explain this much better, but you're far
better
off with using one of the 2 methods above.. HTH, -ak
Mar 15 '08 #2
Thanks, andrei. I'll try that.

Le Sat, 15 Mar 2008 14:25:21 -0700, andrei.avk a écritÂ*:
What you want to do is either 1. load everything up into a string,
replace
text, close file, reopen it with 'w' flag, write string to it. OR if
file is too big, you can read each line, replace, write to a temp file,
then when done move the file over the old one.
Mar 15 '08 #3
On 15 Mar, 21:54, Unknown <cantabile...@wanadoo.frwrote:
I was expecting to replace the old value (serial) with the new one
(todayVal). Instead, this code *adds* another line below the one found...

How can I just replace it?
A file is a stream of bytes, not a list of lines. You can't just
replace a line with another, unless they have the exact same length.
You must rewrite the whole file to get it right.
Mar 17 '08 #4
On Mar 16, 10:35 pm, sturlamolden <sturlamol...@yahoo.nowrote:
On 15 Mar, 21:54, Unknown <cantabile...@wanadoo.frwrote:
I was expecting to replace the old value (serial) with the new one
(todayVal). Instead, this code *adds* another line below the one found...
How can I just replace it?

A file is a stream of bytes, not a list of lines. You can't just
replace a line with another, unless they have the exact same length.
You must rewrite the whole file to get it right.
An example: looks for all 'junk*.txt' files in current directory and
replaces in each line the string 'old' by the string 'new'

<code>
import os, glob, fileinput

allfiles = glob.glob(os.getcwd() + '\\junk*.txt') # makes absolute
paths
findstr = 'old'
replstr = 'new'

countlinesfound = 0
for line in fileinput.input(allfiles,inplace=1):
if line.find(findstr) != -1:
line = line.replace(findstr,replstr) # old string , new
string
countlinesfound += 1
print line, # this writes line back to the file

print countlinesfound
</code>

I found something similar in a tutorial when I started to learn
Python, but I don't remember which one.

Josef
Mar 17 '08 #5
Le Mon, 17 Mar 2008 09:03:07 -0700, joep a écritÂ*:
An example: looks for all 'junk*.txt' files in current directory and
replaces in each line the string 'old' by the string 'new'
Josef
Works like a charm. Many thanks for the example Josef :-)
Mar 18 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: hokieghal99 | last post by:
import os, string print " " setpath = raw_input("Enter the path: ") def find_replace(setpath): for root, dirs, files in os.walk(setpath): fname = files for fname in files: find =...
8
by: Eric Lilja | last post by:
Hello, I had what I thought was normal text-file and I needed to locate a string matching a certain pattern in that file and, if found, replace that string. I thought this would be simple but I had...
3
by: RickN | last post by:
What is the best way to open a file and perform a search and replace for multiple char values. Thanks, RickN
4
by: serge | last post by:
I managed to put together C# code and have it do the following: 1- Get all the table names that start with the letter "Z" from sysobjects of my SQL 2000 database and put these table names...
0
by: Xah Lee | last post by:
Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not...
1
by: Michael Yanowitz | last post by:
Hello: I am hoping someone knows if there is an easier way to do this or someone already implemented something that does this, rather than reinventing the wheel: I have been using the...
4
by: moondaddy | last post by:
I need to edit the text in many files so I'm writing a small routine to do this. First I have a method that loops through all the files in a directory and passes the full file path to another...
3
by: TOXiC | last post by:
Hi everyone, First I say that I serched and tryed everything but I cannot figure out how I can do it. I want to open a a file (not necessary a txt) and find and replace a string. I can do it...
17
by: Levidikus | last post by:
Normally, I never have any problems with String.Replace(). However, I found that I need to replace multiple instances of the character "ª" (\xAA) with a # symbol. The input file is a simple one...
3
by: mouac01 | last post by:
Newbie here. How do I do a find and replace in a binary file? I need to read in a binary file then replace a string "ABC" with another string "XYZ" then write to a new file. Find string is the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.