473,666 Members | 2,044 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to modify a file 'in place' ?

I'm looking for a the most simple and generic way to modify a file, with the
possibility of making backups. In fact, I would like to emulate Perl's -i
option.

here is a bit of code, to explain it further :

< code >

from os import rename

class Modif_File:
def __init__(self, filename, ext='.bak'):
old_name = filename + ext
new_name = filename
rename(new_name ,old_name)

self.old = open(old_name,' r')
self.new = open(new_name,' w')

# methods for getting data are linked to the old file :
for attr in ('encoding', 'newlines', 'next', 'read',
'readinto', 'readline', 'readlines', 'seek',
'tell', 'xreadlines'):
setattr(self,at tr,getattr(self .old,attr))

# methods for putting data are linked to the new one :
for attr in ('closed','flus h','write', 'writelines'):
setattr(self,at tr,getattr(self .new,attr))

def close(self):
self.new.close( )
self.old.close( )

</ code >

for example, an equivalent of
perl -i.bak -pe 's/\t+$//' *txt
could be :

< code >

from glob import glob
from re import compile, MULTILINE

regex = compile(r'\t+$' ,MULTILINE)

for f in [Modif_File(name ) for name in glob('*.txt')]:
f.write(regex.s ub('',f.read()) )
f.close()

</ code >

Of course, this example is very basic and my class Modif_File does not take
into account :
- the right of the file
- the mode of the file (binairy/text)
- ...etc

What is the best way to do it ?

--
Elby

Jul 22 '05 #1
2 1952
Elby wrote:
I'm looking for a the most simple and generic way to modify a file, with the
possibility of making backups. In fact, I would like to emulate Perl's -i
option.

here is a bit of code, to explain it further :

< code >

from os import rename

class Modif_File:
def __init__(self, filename, ext='.bak'):
old_name = filename + ext
new_name = filename
rename(new_name ,old_name)
Quite apart from unusual ideas about what "old" and "new" mean, you have
a problem if filename == "foo" and a physical file named "foo.bak"
exists already.

self.old = open(old_name,' r')
self.new = open(new_name,' w')

# methods for getting data are linked to the old file :
for attr in ('encoding', 'newlines', 'next', 'read',
'readinto', 'readline', 'readlines', 'seek',
'tell', 'xreadlines'):
setattr(self,at tr,getattr(self .old,attr))

# methods for putting data are linked to the new one :
for attr in ('closed','flus h','write', 'writelines'):
setattr(self,at tr,getattr(self .new,attr))


You seem to be majorly confused between a physical file on disk and a
file object used for accessing physical files. There is absolutely
neither need nor usefulness in doing all that getattr/setattr stuff.

Have a look at the documentation for the shutil module. The functions in
that should do most/all of what you want. Then have a look at the
*source* for that module -- which will be present on your machine; on
mine it's C:\Python24\Lib \shutil.py -- and see how elementary physical
file manipulations are done, with no getattr or setattr calls.

HTH,
John
Jul 22 '05 #2
There is a module in the library called fileinput, should do what
you're looking for.

Jul 23 '05 #3

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

Similar topics

0
2410
by: Chris McKeever | last post by:
I am trying to modify the Mailman Python code to stop mapping MIME-types and use the extension of the attachment instead. I am pretty much clueless as to what I need to do here, but I think I have narrowed it down to the Scrubber.py file.. If this seems like a quick step me through, I would be very appreciative, could get you something on your Amazon wish-list (that is me on my knees begging).. From just my basic understanding, it...
5
2082
by: Swarna | last post by:
Hi all, Can anyone help me with this ? I am using scp in python to copy a html file on remote server, to my local machine. Now, i need to update this html file in my local machine ( by adding a new Hyperlink to the existing table od hyperlinks ) and copy it back (overwriting the old copy ) to the remote server. Thanks, for your time !
12
2351
by: Michael B Allen | last post by:
Is it legit to modify static data like the following code? #include <stdlib.h> #include <stdio.h> struct tbl { int i; char *s; };
1
1438
by: justin | last post by:
I have the problem that I need to programatically add new url mappings to the web.config file in an asp 2.0 app. e.g. my code is Dim urlMappings As UrlMappingCollection = urlMappingSection.UrlMappings Dim url_Mapping As UrlMapping Dim y As New UrlMapping("~/myalias", "~/article.aspx?SectionID=45")
5
3200
by: Sandra-24 | last post by:
Is there a way in python to add the items of a dictionary to the local function scope? i.e. var_foo = dict. I don't know how many items are in this dictionary, or what they are until runtime. exec statements are difficult for debuggers to deal with, so as a workaround I built my code into a function and saved it in a .py file. The I load the .py file as a module and call the function instead. This works great, and it has the added...
7
2262
by: mp | last post by:
X-No-Archive How do I go about modifying one character in a string elegantly? In other words, I want a function that will change 'aaaa' to 'aaza', given the index 2 of the character in the string. Also, how do I do this when dealing with a file ; which file mode should I use and what function should I use to modify a single character once in that file mode? Thanks
3
4147
by: DaveO | last post by:
My apologies for individually posting this to multiple newsgroups - my ISP won't allow multiple posts. I'm not a C programmer, so I'm looking for someone to modify some UnZip code for a Self-Extracting stub. I have a copy of the source code of the UnZipSFX utility, also available from : http://sourceforge.net/project/showfiles.php?group_id=118012
23
1958
by: no1zson | last post by:
I have been adding buttons to my GUI to manipulate list data. I added a Delete button this morning in case I decide I no longer needed a particular element. I am now working on a modify button, in case I want to keep the element, but only modify a field or two. This seemed easy after my Delete, but now I am having issues with it. Is there a listModel command out there that I am unfamiliar with that will help me with this? Right now I have...
6
4969
by: Ramesh | last post by:
Hello, I am using the ofstream class to create a text file with keys and values like: Key1=Value10 Key2=Value15 Key3=Value20 In case I need to set a new value for Key2, say value50 - I am able to
0
8444
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
8781
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
8639
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
7386
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
6198
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
5664
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
4198
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
4368
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2011
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.