473,322 Members | 1,352 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,322 software developers and data experts.

Writing to a certain line?

I was wondering if there was a way to take a txt file and, while
keeping most of it, replace only one line. See, I'd have a file like:

Tommy 555
Bob 62
Joe 529

And I'd want to set it to be:

Tommy 555
Bob 66
Joe 529

Is there any easy way to do this?

Jun 6 '06 #1
15 1522
Tommy B:
I was wondering if there was a way to take a txt file and, while
keeping most of it, replace only one line.


You'd need to read the file and parse it, to find the start position of
the line you want to change. Then seek output to that position and write
and flush the changes. You must keep the file locked during this
operation, to prevent other processes from changing the file in between
these steps. You can only replace a string with a string of the same
length.
http://docs.python.org/lib/bltin-file-objects.html

--
René Pijlman
Jun 6 '06 #2
Tommy B wrote:
I was wondering if there was a way to take a txt file and, while
keeping most of it, replace only one line.


<meta>
This is a FAQ (while I don't know if it's in the FAQ !-), and is in no
way a Python problem. FWIW, this is also CS101...
</meta>

You can't do this in place with a text file (would be possible with a
fixed-length binary format).

The canonical way to do so - whatever the language, is to write the
modified version in a new file, then replace the old one.

import os
old = open("/path/to/file.txt", "r")
new = open("/path/to/new.txt", "w")
for line in old:
if line.strip() == "Bob 62"
line = line.replace("62", "66")
new.write(line)
old.close()
new.close()
os.rename("/path/to/new.txt", "/path/to/file.txt")

If you have to do this kind of operation frequently and don't care about
files being human-readable, you may be better using some lightweight
database system (berkeley, sqlite,...) or any other existing lib that'll
take care of gory details.

Else - if you want/need to stick to human readable flat text files - at
least write a solid librairy handling this, so you can keep client code
free of technical cruft.

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 6 '06 #3
bruno at modulix wrote:
<meta>
This is a FAQ (while I don't know if it's in the FAQ !-), and is in no
way a Python problem. FWIW, this is also CS101...
</meta>


feel free to repost your response here:

http://pyfaq.infogami.com/suggest

</F>

Jun 6 '06 #4
bruno at modulix:
You can't do this in place with a text file (would be possible with a
fixed-length binary format).


More precise: it's possible with any fixed-length change, in both binary
and text files, with both fixed and variable formats.

--
René Pijlman
Jun 6 '06 #5
Rene Pijlman wrote:
bruno at modulix:
You can't do this in place with a text file (would be possible with a
fixed-length binary format).

More precise: it's possible with any fixed-length change, in both binary
and text files, with both fixed and variable formats.

Granted. But this is somewhat limited in what you can do when working
with text files...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 6 '06 #6

bruno at modulix wrote:

Else - if you want/need to stick to human readable flat text files - at
least write a solid librairy handling this, so you can keep client code
free of technical cruft.

HTH
--
bruno desthuilliers


for human readable, you might want to look at reading and writing dicts
in YAML and SYCK libs, which is what this looks like

Jun 6 '06 #7

bruno at modulix wrote:
Tommy B wrote:
I was wondering if there was a way to take a txt file and, while
keeping most of it, replace only one line.


<meta>
This is a FAQ (while I don't know if it's in the FAQ !-), and is in no
way a Python problem. FWIW, this is also CS101...
</meta>

You can't do this in place with a text file (would be possible with a
fixed-length binary format).

The canonical way to do so - whatever the language, is to write the
modified version in a new file, then replace the old one.

import os
old = open("/path/to/file.txt", "r")
new = open("/path/to/new.txt", "w")
for line in old:
if line.strip() == "Bob 62"
line = line.replace("62", "66")
new.write(line)
old.close()
new.close()
os.rename("/path/to/new.txt", "/path/to/file.txt")

If you have to do this kind of operation frequently and don't care about
files being human-readable, you may be better using some lightweight
database system (berkeley, sqlite,...) or any other existing lib that'll
take care of gory details.

Else - if you want/need to stick to human readable flat text files - at
least write a solid librairy handling this, so you can keep client code
free of technical cruft.

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"


Umm... I tried using this method and it froze. Infiinite loop, I'm
guessing.

Jun 6 '06 #8
Tommy B wrote:
import os
old = open("/path/to/file.txt", "r")
new = open("/path/to/new.txt", "w")
for line in old:
if line.strip() == "Bob 62"
line = line.replace("62", "66")
new.write(line)
old.close()
new.close()
os.rename("/path/to/new.txt", "/path/to/file.txt")
Umm... I tried using this method and it froze. Infiinite loop, I'm
guessing.


you have an infinitely large disk with an infinitely large file on it?

</F>

Jun 6 '06 #9
On 7/06/2006 7:46 AM, Tommy B wrote:

Umm... I tried using this method and it froze. Infiinite loop, I'm
guessing.


Don't guess.

Instead:

(1) Put some print statements into your code to show what is happening:
(a) before start of loop (b) one or more salient points inside loop (c)
at (expected) loop termination point.

(2) If that doesn't point you at the problem, ask again, showing the
actual whole .py file that you ran -- copy/paste, don't re-type what you
thought you might have run :-)

It would also help if you described what "froze" means. Evidence of disk
activity? Evidence of CPU activity? Did recovery involve merely closing
the process's window, or did you need to re-boot?

Also potentially helpful in getting better help: what version of Python;
what operating system; are you running your code in an IDE (e.g. IDLE)
or at the command line?

HTH,
John
Jun 6 '06 #10
Tommy B wrote:
bruno at modulix wrote:
(snip)
import os
old = open("/path/to/file.txt", "r")
new = open("/path/to/new.txt", "w")
for line in old:
if line.strip() == "Bob 62"
line = line.replace("62", "66")
new.write(line)
old.close()
new.close()
os.rename("/path/to/new.txt", "/path/to/file.txt")

(snip)
Umm... I tried using this method and it froze. Infiinite loop, I'm
guessing.


Wrong guess - unless, as Fredrik suggested, you have an infinite disk
with an infinite file on it. If so, please share with, we would be
*very* interested !-)

Seriously : a for loop can only become an infinite loop if the iterable
is infinite. AFAIK, file objects (created from regular files on a
standard filesystem) are definitively not infinite.

Problem is elsewhere. But since you prefered to guess - instead of
providing relevant informations - we just can't help.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 7 '06 #11
bruno at modulix a écrit :
Tommy B wrote:
bruno at modulix wrote:

(snip)

import os
old = open("/path/to/file.txt", "r")
new = open("/path/to/new.txt", "w")
for line in old:
if line.strip() == "Bob 62"
line = line.replace("62", "66")
new.write(line)
old.close()
new.close()
os.rename("/path/to/new.txt", "/path/to/file.txt")


(snip)
Umm... I tried using this method and it froze. Infiinite loop, I'm
guessing.

Wrong guess - unless, as Fredrik suggested, you have an infinite disk
with an infinite file on it. If so, please share with, we would be
*very* interested !-)


Use /dev/zero as source and /dev/null as destination :D
Jun 7 '06 #12
Christophe wrote:
bruno at modulix a écrit :

(snip)
Wrong guess - unless, as Fredrik suggested, you have an infinite disk
with an infinite file on it. If so, please share with, we would be
*very* interested !-)

Use /dev/zero as source and /dev/null as destination :D


Lol !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 7 '06 #13
Christophe wrote:
Use /dev/zero as source and /dev/null as destination :D


have you tried looping over an endless null-byte stream?

on a random Linux server, this statement
for line in open("/dev/zero"): .... print len(line)
....

terminates without printing anything after about three seconds, which is
a bit odd. in contrast,
f = open("/dev/zero")
len(f.readline())


raises a MemoryError exception after about 10 seconds. hmm. looks like
a bug in the file iterator, really...

</F>

Jun 7 '06 #14
On Wed, Jun 07, 2006 at 08:17:22PM +0200, Fredrik Lundh wrote:
Christophe wrote:
Use /dev/zero as source and /dev/null as destination :D


have you tried looping over an endless null-byte stream?

on a random Linux server, this statement
>>> for line in open("/dev/zero"): ... print len(line)
...

terminates without printing anything after about three seconds, which is
a bit odd. in contrast,
>>> f = open("/dev/zero")
>>> len(f.readline())


raises a MemoryError exception after about 10 seconds. hmm. looks like
a bug in the file iterator, really...


svn log Objects/fileobject.c

r43506 | georg.brandl | 2006-03-31 15:31:02 -0500 (Fri, 31 Mar 2006) | 2 lines

Bug #1177964: make file iterator raise MemoryError on too big files
So it always the error on the trunk.

-Jack
Jun 7 '06 #15
"Tommy B" <to*****@gmail.com> writes:
I was wondering if there was a way to take a txt file and, while
keeping most of it, replace only one line. See, I'd have a file like:
...
Is there any easy way to do this?


An easy way? If you know how many bytes in from the start of the file
your desired changes are to be positioned, the utility of choice is
the strange but wonderful "dd" for Unix, MSwindows, MSDOS, etc.
That's its name: dd. Are you planning to execute a call to dd from within
a python program? Of course, you are constrained to substituting N bytes
with another N bytes, exactly.
--
John Savage (my news address is not valid for email)

Jun 9 '06 #16

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

Similar topics

6
by: Marian Aldenhövel | last post by:
Hi, I am using the FMOD audio-library with the pyFMOD python bindings. pyFMOD uses ctypes. It is possible to register callback functions with FMOD that are called at certain points in the...
10
by: C Williams | last post by:
Hi, In a nutshell, my question is: how do i make a dll that I compile from vb.net code register and work like one compiled as an ActiveX dll in VB6? The IDE of my copy of visual basic.net does...
2
by: melanieab | last post by:
Hi, I'm trying to store all of my data into one file (there're about 140 things to keep track of). I have no problem reading a specific string from the array file, but I wasn't sure how to...
1
by: JuneCleaver | last post by:
Hello, I have been digging into writing into a file with the dot net framework. There is a lot of information on it. I have a web application and I want to write to a log file when an...
4
by: John Pote | last post by:
Hello, help/advice appreciated. Background: I am writing some web scripts in python to receive small amounts of data from remote sensors and store the data in a file. 50 to 100 bytes every 5 or...
7
by: utab | last post by:
Hi there, I am trying to read from a file and at the same time change certain fields of the same field, there are 6 fields in this file like 1 2 3 4 5 6...
0
by: Steve Holden | last post by:
Mohsen Akbari wrote: Then, later:...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.