473,695 Members | 1,870 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to write a line in a text file

Hey there,
kinda newbie question here.
i know how to read the lines of a txt file.
i know how to write a txt file.

but how do i overwrite a line value with another value ?

i mean, how do go to, say, line 3 of a text file and replace
what is written on line 3 with something else?

thanks
<><

Jul 25 '05 #1
16 3025
ne*****@xit.net wrote:
Hey there,
kinda newbie question here.
i know how to read the lines of a txt file.
i know how to write a txt file.

but how do i overwrite a line value with another value ?

i mean, how do go to, say, line 3 of a text file and replace
what is written on line 3 with something else?

thanks
<><

You shouldn't try do "update in place" like that unless your file has
fixed-length lines or records. Altering the length of an existing file
isn't to be lightly undertaken, and even when possible will likely not
be undertaken.

The classic way to approach this problem is to read the file as input,
processing its contents and writing a new file, which eventually
replaces the original in a fairly complex dance of renaming and deletion.

In Python you can use a text file's readlines() method to build a list
of all the lines in a file. That makes it quite easy to change numbered
lines. Having modified the file's content in memory you can then create
a new file using the writelines() method of a new file. The trick is to
avoid losing both the old and the new files when a low-probability crash
occurs.

Since you are newbile (?) I would advise against paranoia - write your
code without worrying about error handling. You'll be pleased to know
that when you start to take a serious interest in error handling Python
has everything you'll need.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jul 25 '05 #2
A recipe is
* open your file for reading: f = open('filename. txt', 'r')
* read all lines in a list: content = f.readlines()
* close the file: f.close()
* set the third element in the list to something else: content[2] =
'Blahdiblah'
* re-open the file for writing: f = open('filename. txt', 'w')
* write the list to the file: f.writelines(co ntent)
* close the file: f.close()

Jul 25 '05 #3
Gee whiz, so easy.
thanks. Never thought about just changing it while it was read then
re-writing it. that will be just fine. these files are only 9 lines
long.
thanks again !

Jul 25 '05 #4
On 25 Jul 2005 12:57:55 -0700,
"wi******@hotma il.com" <ma**********@g mail.com> wrote:
A recipe is
* open your file for reading: f = open('filename. txt', 'r')
* read all lines in a list: content = f.readlines()
* close the file: f.close()
* set the third element in the list to something else: content[2] =
'Blahdiblah'
Better make that ''Blahdiblah\n' (note the trailing newline) because:
- readlines leaves the newlines at the ends of the lines
- writelines assumes that each line (still) contains a newline
* re-open the file for writing: f = open('filename. txt', 'w')
* write the list to the file: f.writelines(co ntent)
* close the file: f.close()


HTH,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Jul 25 '05 #5
On Mon, 25 Jul 2005 20:51:42 +0100, Steve Holden wrote:
In Python you can use a text file's readlines() method to build a list
of all the lines in a file. That makes it quite easy to change numbered
lines. Having modified the file's content in memory you can then create
a new file using the writelines() method of a new file. The trick is to
avoid losing both the old and the new files when a low-probability crash
occurs.


I'm usually opposed to creeping featuritis in programming languages ("it
would be really cool if Python had a built-in command to do my entire
application") but safe over-writing of files does cry out for a "batteries
included" approach:

- it is a common usage;
- it is tricky to get right;
- it is even trickier to get right in a platform independent way;
- and it is even trickier again to get right in a platform independent way
that doesn't introduce security risks.

The normal trick is to do something like:

read file A;
write temporary file B without clobbering any existing B;
rename file A to C;
rename B to A;
delete C when you know the writing and renaming has succeeded;
and do it all in such a way that it succeeds even if there is very little
available disk-space.

The platform-independence comes from the fact that different OSes expect
the temporary files to live in different places (eg /tmp/ under Linux).
Most operating systems consider it poor form to just write temporary files
any old place.

I'm told by those who claim to know what they're talking about that a
potential risk exists if an attacker can predict the temporary file name
and thus do nefarious things. The exact nature of those nefarious things
was not explained to me, but I do recall the occasional security advisory
for applications which use insufficiently-random temporary file names.

Does anyone have anything suitable for a "safe-overwrite" module?

--
Steven.

Jul 25 '05 #6
Steven D'Aprano wrote:
I'm usually opposed to creeping featuritis in programming languages ("it
would be really cool if Python had a built-in command to do my entire
application" ) but safe over-writing of files does cry out for a "batteries
included" approach:

How about the fileinput module?

http://docs.python.org/lib/module-fileinput.html

"""
Optional in-place filtering: if the keyword argument inplace=1 is
passed to input() or to the FileInput constructor, the file is moved to
a backup file and standard output is directed to the input file (if a
file of the same name as the backup file already exists, it will be
replaced silently). This makes it possible to write a filter that
rewrites its input file in place. If the keyword argument
backup='.<some extension>' is also given, it specifies the extension
for the backup file, and the backup file remains around; by default,
the extension is '.bak' and it is deleted when the output file is
closed. In-place filtering is disabled when standard input is read.
"""

Jul 25 '05 #7
Wade wrote:
Steven D'Aprano wrote:
I'm usually opposed to creeping featuritis in programming languages ("it
would be really cool if Python had a built-in command to do my entire
application ") but safe over-writing of files does cry out for a "batteries
included" approach:


How about the fileinput module?

http://docs.python.org/lib/module-fileinput.html


Close, but not quite: the "inplace" argument is more
specific and less general than what I was talking about.

The fileinput solution only works for the specific idiom:

read file A in text mode
process text
write standard output back to file A

compared to the more general idiom:

get data from somewhere
process data
write data to existing file A

In the more general idiom, you don't care whether your
data is text or binary data, whether you got it from a
file, whether it was the same file you are writing to,
or anything else. All you care about is that the file
you write to happens to already exist.

Long ago, when dinosaurs roamed the Earth, (a.k.a.
"before OS X on the Macintosh") Apple suggested a bit
of Pascal code for safely updating a file:

http://developer.apple.com/documenta...l#MARKER-9-163

Most of the code is Macintosh-specific, but the
principle is not: when over-writing a file, make sure
that the user can recover from any error up to and
including power failure without losing the data on disk.

(Presumably if the sun explodes and destroys the Earth,
your program is allowed to lose data.)
--
Steven.

Jul 26 '05 #8
Tue, Jul 26, 2005 at 01:41:36PM +1000, Steven D'Aprano пишет:
Long ago, when dinosaurs roamed the Earth, (a.k.a.
"before OS X on the Macintosh") Apple suggested a bit
of Pascal code for safely updating a file:

http://developer.apple.com/documenta...l#MARKER-9-163
That snippet doesn't write data to the existing file. It writes data into
the new tempfile and then renames it, as well as the FileInput object does.
Most of the code is Macintosh-specific, but the
principle is not: when over-writing a file, make sure
that the user can recover from any error up to and
including power failure without losing the data on disk.


Well, it's what (R)DBMS are for, but plain files are not.

--
jk
Jul 26 '05 #9
en**********@os paz.ru wrote:
Tue, Jul 26, 2005 at 01:41:36PM +1000, Steven D'Aprano пишет:
Long ago, when dinosaurs roamed the Earth, (a.k.a.
"before OS X on the Macintosh") Apple suggested a bit
of Pascal code for safely updating a file:

http://developer.apple.com/documenta...l#MARKER-9-163

That snippet doesn't write data to the existing file. It writes data into
the new tempfile and then renames it, as well as the FileInput object does.


Obviously you can't *directly* overwrite a file and
expect good things to happen if the disk crashes
half-way through. Any sort of safe overwrite must use
an intermediate file somewhere. That goes without saying.

As for the FileInput object doing the job "as well as"
the old Mac file system, no it does not. I've already
described how the FileInput object is only usable in a
vanishingly small subset of all potential file
overwrites, namely when you are writing stdout to the
same text file you read from -- or at least one of the
multiple files you read from.

If that solution works for your needs, you should use
it. But if you are not writing to stdout, your data
isn't text, and you didn't get it from the same file
you are overwriting, the FileInput solution is no
solution at all.
Most of the code is Macintosh-specific, but the
principle is not: when over-writing a file, make sure
that the user can recover from any error up to and
including power failure without losing the data on disk.

Well, it's what (R)DBMS are for, but plain files are not.


This isn't 1970, users expect more from professional
programs than "keep your fingers crossed that nothing
bad will happen". That's why applications have multiple
levels of undo (and some of them even save the undo
history in the file) and change-tracking, and auto-save
and auto-backup. Even in the less-than-user-friendly
world of Linux many applications implement their own
version of data protection.

Now maybe you feel that it is overkill for your program
to bother about the tiny chance of data loss when
saving data. That's fine. For 99% of my scripts, I
don't even bother with try...except blocks when writing
to a file. I just open it and write to it and hope it
all works.

But for that other 1%, I take the time to check for
errors and allow the program to recover gracefully. And
that means, if you are about to save the user's work,
you better be sure that if the save fails for any
reason, you haven't blown away their precious data. If
you want to live dangerously with your own data, go for
it. But destroying the user's data is the biggest
programming sin of all.
--
Steven.

Jul 26 '05 #10

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

Similar topics

4
2926
by: JDJones | last post by:
I'm trying to write a script that will read from a text list of songs that I burned onto my CD (Albums011.txt), then write to the database text the new text made ready for inserting into a database. The entries from the Albums011.txt look like this: Wayne Newton - Wild Cool & Swingin' - 03 - But Not For Me.mp3 Wayne Newton - Wild Cool & Swingin' - 04 - Wives And Lovers.mp3 etc. and I want to manipulate it them to look in the...
3
2661
by: John Flynn | last post by:
hi, having problems reading from and writing back to the same file. basically, i want to read lines of text from a file and reverse them and write them back to the same file.. it has to replace the text its reversing eg.
1
4303
by: Magix | last post by:
Hi, I have these string data: str_data1, str_data2, str_data3, which capture some value after a routine process A. Then I would like to write (append) these 3 string values into a text file each time after routine process A, the text file is named "mytext.dat" in following format with "#####" as separator. The maximum entries of them is 5. When reaching the fifth entry, it will delete the very first entry.
5
3159
by: Martin Svensson | last post by:
Hello! I need some help/recommendations on how to do the following. I have a program that writes an IP address two control numbers and a date to file, on one line. It's a basic text file and it looks like this: ----- beginning of file ----- 192.168.0.1 0 0 2004-08-01 192.168.0.2 1 0 2004-08-21 192.168.0.4 0 1 2004-08-12
12
11114
by: Nina | last post by:
Hi there, What is the maximum length that one line can hold in a text file using StreamWriter's Write or WriteLine method? If the string is too long for one line to hold, what will Write or WriteLine do? In order me to retrieve data correctly from the text file later, I have to know the right index. For the following code,if str1's length exceeds one line in text file, how can I get str2's index when reading the text file? Is there...
0
789
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. Stack Trace at System.Net.Sockets.NetworkStream.Write(Byte buffer, Int32 offset, Int32
3
14051
by: Buddy Home | last post by:
Hello, I'm trying to upload a file programatically and occasionally I get the following error message. Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. Stack Trace at System.Net.Sockets.NetworkStream.Write(Byte buffer, Int32 offset, Int32
24
4438
by: Bill | last post by:
Hello, I'm trying to output buffer content to a file. I either get an access violation error, or crazy looking output in the file depending on which method I use to write the file. Can anyone help out a newbie? #include <stdio.h> #include <ctype.h> #include <string.h>
6
18296
by: globalrev | last post by:
i ahve a program that takes certain textsnippets out of one file and inserts them into another. problem is it jsut overwrites the first riow every time. i want to insert every new piece of text into the next row. so: 1. how do i write to a new line every time i write to the file? 2. if i dont want to write to a new line but just want to insert it
65
5071
by: Hongyu | last post by:
Dear all: I am trying to write to a file with full directory name and file name specified (./outdir/mytestout.txt where . is the current directory) in C programming language and under Unix, but got errors of Failed to open file ./outdir/mytestout.txt. Below is the code: #include <stdio.h>
0
8650
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8586
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
9140
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...
0
9004
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8864
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
8838
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7685
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 projectplanning, coding, testing, and deploymentwithout 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...
0
5843
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4597
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.