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

simultaneous reading and writing a textfile

Hi,

I have a text file with some lines in it.
Now I want to iterate over this file and exchange some lines with some
others. I tried this approach:

try:
myfile= file('myfile', 'r+')

while 1:
line= myfile.readline()
if not line: break

l= line.strip().split()
if len(l) == 1:
hostname= l[0]
myfile.write(hostname+' '+mac+'\n')
break

finally:
if not myfile is None:
myfile.close()
This should inspect the file and find the first line, that can't be
split into two parts (that means, which has only one word in it).
This line should be exchanged with a line that contains some more
info.

Unfortunately (or how better python programmers than I am would say,
"of course") this doesn't work. The line is exchanged, but also some
more lines.

Now how can I achieve, what I want? Really exchange one line with
another, regardless of their length. Is this possible? If this is not
possible, then what would be the best approach to do this?

I do not want to read the whole file, exchange the line in memory and
then write the whole file. This would be quite slow with large files.

Regard1s
Marco
May 16 '06 #1
3 4680
Marco Herrn wrote:
Hi,

I have a text file with some lines in it.
Now I want to iterate over this file and exchange some lines with some
others. I tried this approach:

try:
myfile= file('myfile', 'r+')

while 1:
line= myfile.readline()
if not line: break

l= line.strip().split()
if len(l) == 1:
hostname= l[0]
myfile.write(hostname+' '+mac+'\n')
break

finally:
if not myfile is None:
myfile.close()
This should inspect the file and find the first line, that can't be
split into two parts (that means, which has only one word in it).
This line should be exchanged with a line that contains some more
info.

Unfortunately (or how better python programmers than I am would say,
"of course") this doesn't work. The line is exchanged, but also some
more lines.

Now how can I achieve, what I want? Really exchange one line with
another, regardless of their length. Is this possible? If this is not
possible, then what would be the best approach to do this?

I do not want to read the whole file, exchange the line in memory and
then write the whole file. This would be quite slow with large files.

Regard1s
Marco


The only way that in-place writes will work is if you adopt a fixed
line length for the file and use read(bytes) instead of readline()
method. You could create file with fixed length lines and write them
in-place without disturbing lines that follow. Take a look at seek(),
write() methods.

The alternative is to create a different file (read/write
the entire file)each time you want to make a change. Unless the file
is REALLY long, this will be extremely fast.

If you have a LOT of data you want to work with this way and it is
changing a lot, you need to use a database not a text file for data
storage.

-Larry
May 16 '06 #2
Marco Herrn wrote:
I have a text file with some lines in it.
Now I want to iterate over this file and exchange some lines with some
others. I tried this approach: This should inspect the file and find the first line, that can't be
split into two parts (that means, which has only one word in it).
This line should be exchanged with a line that contains some more
info.

Unfortunately (or how better python programmers than I am would say,
"of course") this doesn't work. The line is exchanged, but also some
more lines.

Now how can I achieve, what I want? Really exchange one line with
another, regardless of their length. Is this possible? If this is not
possible, then what would be the best approach to do this?
A file is exposed as a sequence of bytes. You can only exchange a string of
bytes with the same number of (different) bytes. Inserting or removing
bytes means you have to rewrite the file from the insertion/deletion point
onwards. Usually you don't bother and just rewrite the whole file.
I do not want to read the whole file, exchange the line in memory and
then write the whole file. This would be quite slow with large files.


Here's a simple approach that can deal with large files:

# does not work on windows
BLOCKSIZE = 2**20
infile = open(filename)
os.unlink(filename) # rename if you want to play it safe
outfile = open(filename, "w")
lines = iter(infile.readline, "")
# copy one line at a time
for line in lines:
parts = line.split(None, 1)
if len(parts) == 1:
outfile.write("%s %s\n" % (parts[0], mac))
break
outfile.write(line)
# after the insertion point proceed with larger steps
for block in iter(lambda: infile.read(BLOCKSIZE), ""):
outfile.write(block)
infile.close()
outfile.close()

When this becomes too slow you should consider a database.

Peter
May 16 '06 #3
On 2006-05-16, Peter Otten <__*******@web.de> wrote:
Now how can I achieve, what I want? Really exchange one line with
another, regardless of their length. Is this possible? If this is not
possible, then what would be the best approach to do this?


A file is exposed as a sequence of bytes. You can only exchange a string of
bytes with the same number of (different) bytes. Inserting or removing
bytes means you have to rewrite the file from the insertion/deletion point
onwards. Usually you don't bother and just rewrite the whole file.


Thanks to you both. I will use that. I do not think, that the files
will be that large, that a database is useful. The main advantage of
the file is, that it is directly human readible.

Regards
Marco
May 17 '06 #4

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

Similar topics

2
by: Dot Kom | last post by:
I've got this text file full of lines like: A*1King Richard Dale*3Welton Orchard Rd*4Petersburg*5257-1234Î the columns are defined by the *#, so that line would break apart like: A*1King...
2
by: BjoernJackschina | last post by:
Hello, I just look for a capability to sort several words in view of alphabet. An example: stop is 'opst' reach is 'aechr' This should read in a new file so that I can look for same letter...
8
by: smeenehan | last post by:
This is a bit of a peculiar problem. First off, this relates to Python Challenge #12, so if you are attempting those and have yet to finish #12, as there are potential spoilers here. I have five...
5
by: UJ | last post by:
I have a system that has five programs that all communicate with each other via Message Queues. Works well. One program is a watchdog that will make sure the others are up and going. Currently I...
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
1
by: ChrisFrohlich | last post by:
ASP.NET 2.0 with Text DataTypes: I've got a similar question going in the SQL group, but I was wondering if anyone has successfully implemented reading/writing character data from a Text datatype...
6
by: =?Utf-8?B?UmljaA==?= | last post by:
'--this code works but only reads text into one column when contains multiple cols Dim ds1x As New DataSet Dim ConStr As String = _ "Provider=Microsoft.Jet.OLEDB.4.0;Data...
2
by: banerr2 | last post by:
I'm a beginner in C++. I'm in the process of writing an 'Automated Library Management System' using C++ on a Windows machine. I'm stuck in the midst of reading/writing data from a .csv file that...
3
by: Deivys Ramirez | last post by:
Hi everyone, I'm a Python newbie but have experience programming PHP and C so i'm not really new to programming but new to Python. What's the "pythonic" way of reading a text file, line by...
3
by: Arn | last post by:
I just started to learn C++ and have some problem when I read a hole line from a textfile. I would be grateful if anyone can tell me what is wrong with my code. I'm using Borland Developer Studio...
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...

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.