473,651 Members | 3,004 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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().sp lit()
if len(l) == 1:
hostname= l[0]
myfile.write(ho stname+' '+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 4699
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().sp lit()
if len(l) == 1:
hostname= l[0]
myfile.write(ho stname+' '+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(filen ame) # rename if you want to play it safe
outfile = open(filename, "w")
lines = iter(infile.rea dline, "")
# 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(l ine)
# after the insertion point proceed with larger steps
for block in iter(lambda: infile.read(BLO CKSIZE), ""):
outfile.write(b lock)
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
2871
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 Richard Dale *3Welton Orchard Rd *4Petersburg *5257-1234Î Basically, what I need to do is read this file and I need to write
2
2575
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 orders. When I find the same orders it is an anagram. My problem is to sort and to select the textfile. I need dataset for dataset. What is the best way to realize that.
8
2667
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 different image files shuffled up in one big binary file. In order to view them I have to "unshuffle" the data, which means moving bytes around. Currently my approach is to read the data from the original, unshuffle as necessary, and then write...
5
5065
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 have it store info it gets from when the programs check in into a DataSet (XML file). Problem is, that file now has to be used by other programs to find out version information (the file is ALWAYS less that 1K.) The record itself is only five fields...
6
5260
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
1644
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 column in SQL 2000. I know there's a Varchar(MAX) feature in SQL2005, but my budget mocks me right now and I need to do it in SQL 2K. Situation: I'm building a resume DB, and for ease of input, I'd really like to be able to use a single...
6
22517
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 Source=C:\dir1A\;Extended Properties=""Text;HDR=No;FMT=Delimited\""" Dim conn1x As New OleDb.OleDbConnection(ConStr) Dim dax1 As New OleDbDataAdapter("Select * from testabc1x.txt", conn1x)
2
10735
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 holds the information about materials available in the library. Any help is greatly appreciated!
3
1241
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 line, without throwing an exception when there's nothing to be read? I've been trying to map my while(!eof(fp)) mindset to the file object Python gives me when I call open() but have had no good results.
3
2896
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 2006. //------------------------------------------------------------------------------ // getFile //------------------------------------------------------------------------------ // Read from a textfile // Input: nameList (string) , FILENAME...
0
8357
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8277
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8803
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8465
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7298
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6158
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2701
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1910
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.