473,748 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

deleting a line from a file

Hello,

In Perl, using a Tie::File module I can easily and comfortably delete
a line from the middle of a text file:

my @file;
open(DATA, "+<:encoding(ut f8):raw" , "file.txt") or return 0;
tie @file, 'Tie::File', \*DATA or return 0;
splice(@file, $_[0], 1);
untie @file;
close DATA;

(when the first argument of the function ($_[0]) is a number of the
line which should be deleted)

Is there some easy way how to delete a line from a middle of a file in
Python?

Thanks a lot
eMko
Mar 29 '08 #1
2 12328
On Sat, 29 Mar 2008 04:13:10 -0700, eMko wrote:
Is there some easy way how to delete a line from a middle of a file in
Python?
If the file is small enough to fit into memory (say, up to a few hundred
megabytes on most modern PCs):
lines = open('file', 'r').readlines( )
del line[100]
open('file', 'w').writelines (lines)
Quick and easy for the coder, but not the safest way to do it in serious
production code because there's no error handling there.

The only safe way to delete a line from a file (at least under common
operating systems like Windows, Linux and Mac) is to copy the file
(without the line you wish to delete) to a temporary file, then replace
the original file with the new version. That's also how to do it for
files too big to read into memory.

--
Steven
Mar 29 '08 #2
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com .auwrites:
The only safe way to delete a line from a file (at least under common
operating systems like Windows, Linux and Mac) is to copy the file
(without the line you wish to delete) to a temporary file, then replace
the original file with the new version. That's also how to do it for
files too big to read into memory.
You could do it "in place" in all those systems afaik, either opening
the file for both reading and writing, or using something like mmap.
Basically you'd leave the file unchanged up to line N, then copy lines
downward starting from line N+1. At the end you'd use ftrunc to
shrink the file, getting rid of the duplicate last line.
Mar 29 '08 #3

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

Similar topics

2
7401
by: Bill Sneddon | last post by:
Anyone have an example they are willing to share that shows how to use the store command in imaplib? store( message_set, command, flag_list) Alters flag dispositions for messages in mailbox. I have been unable to find one or get the syntax correct through trial and error. I can send the command to the server in the following manor.
5
2734
by: flupke | last post by:
Hi, i'm having trouble with deleting elements from a list in a for loop ============== test program ============== el = print "**** Start ****" print "List = %s " % el index = 0 for line in el:
4
2950
by: Mark | last post by:
Not sure this is the right place for this questions, but here goes: I get an error message when deleting an table from a Access database. The code is as follows and the error message is after it. ***************** Start Code ******************** <%@ import Namespace="System.Data" %> <%@ import Namespace="System.Data.Oledb" %>
13
9535
by: Bob Darlington | last post by:
I have a repair and backup database routine which runs when a user closes down my application. It works fine in my development machine, but breaks on a client's at the following line: If Dir(strLDB) <> "" Then Kill (strLDB) where strLDB is the path to the ldb file. The client advises that the ldb doesn't lurk after the program closes. Any ideas?
2
2131
by: melanieab | last post by:
Hi, I'm deleting nodes in my xml file, and it does seem to work, but then when I later reload the file and make an xmlNodeList, the nodelist count still includes the deleted nodes yet the file shows no sign of them. Here is what I have: Example of my xml: <Catalog> <File ID = "1"> <Customer>Me</Customer>
0
1408
by: Bandit | last post by:
I'm populating a gridview (called docList) with document info from a network folder like so: Sub Show_Files(ByVal inputDir As String) Dim strFileNamePath As String = inputDir Dim dirInfo As DirectoryInfo = New DirectoryInfo(strFileNamePath) Dim aFiles As FileInfo() = dirInfo.GetFiles("*.doc") Array.Sort(aFiles, New CompareFileInfoEntries (CompareByOptions.LastWriteTime)) docList.DataSource = aFiles
2
2390
by: angus | last post by:
hello everybody, i'm having some problems searching a text file and then deleting the line. since i used fileopen(), i can use the eof() function to loop through the file, searching for the specified line. the problem is, once found, i can't delete it because the filemode is in openmode.input. is there a way to chance the openmode on the run?(if so, what is it?) and maybe there is a simpler way to search a text file and deleting the...
2
1714
by: SiouxieQ | last post by:
Hi there, I'm using the code below to try to delete a name from a list of names in a file. Unfortunately it doesn't quite do what I want it to. Instead of looking for the name in the textbox and deleting that it is just deleting the first line of data in the file.
13
2464
by: programming | last post by:
how do i delete from a text file 1 of the following lines: jon|scott adam|smith <--delete paul|clark say i would like to delete the middle line of this txt, in member.txt what php code or logic would help me accomplish this?
4
1537
by: blackice | last post by:
Hello All, i have a Perl Script that deleting Zones from named.conf file and here is the script #!/usr/bin/perl -w use strict; print "please enter the domain name: "; chomp (my $targetdomain = <STDIN>);
0
8994
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
9555
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
9376
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...
0
9250
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...
1
6796
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
4607
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...
0
4878
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.