473,791 Members | 3,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Having trouble with file modes

Hi all,

I've created a script that reads in a file, replaces some data (regex),
then writes the new data back to the file.

At first I was convinced that "w+" was the tool for the job. But now
I'm finding that the contents of the file are deleted (so I can't read
the data in).

f = open('_i_define s.php', 'w+')
data = f.read()
#patterns removed for brevity.
patterns = [(tuples)(blah blah)]

#loop through patterns list and find/replace data
for o, r in patterns:
data = data.replace(o, r)
print "Replaced %s with %s" % (o, r)
f.write(data)
f.close()

This results in an empty file. All of the modes I've tried either
produce an empty file or append the data onto the end of the file. How
Can I:

Open
Read
Truncate
....process data....
Write
Close

Do I need to open and close the file twice? (once in 'r' and then again
in 'w')

Thanks!
Erik

Nov 3 '06 #1
5 1307
At first I was convinced that "w+" was the tool for the job. But now
I'm finding that the contents of the file are deleted (so I can't read
the data in).

Possible File Modes:
a : Append -- Add data at the end of the file
r : Read -- Read from the file
w : write -- Flush contents of the file and put data in it
r+ : read and write -- Make changes to the file
any of the above modes with b added at the end of the mode sets the
file in binary mode

you might want to check section 7.2 from
http://docs.python.org/tut/node9.html

Ofen when doing file operations you might prefer to read the file to
modify, make changes in memory then save back in an other file, so you
can make sure the changes are ok before you replace the old one

Nov 3 '06 #2
Don't do that. Do something like renaming the old file
to .bak (or .aside or something) and then create the entire file
by opening it with 'w'.

-Larry
Nov 3 '06 #3
To make it write over the data, I ended up adding, which seems to work
fine.

f = open('_i_define s.php', 'w+')
data = f.read()
f.seek(0)
f.truncate(0)
....process data, write file, close...

Now that I look at it, I could probably take out the f.seek().

Thanks for your help!
On Nov 3, 4:00 pm, "martdi" <martin.d...@gm ail.comwrote:
At first I was convinced that "w+" was the tool for the job. But now
I'm finding that the contents of the file are deleted (so I can't read
the data in).Possible File Modes:
a : Append -- Add data at the end of the file
r : Read -- Read from the file
w : write -- Flush contents of the file and put data in it
r+ : read and write -- Make changes to the file
any of the above modes with b added at the end of the mode sets the
file in binary mode

you might want to check section 7.2 fromhttp://docs.python.org/tut/node9.html

Ofen when doing file operations you might prefer to read the file to
modify, make changes in memory then save back in an other file, so you
can make sure the changes are ok before you replace the old one
Nov 3 '06 #4
"erikcw" <er***********@ gmail.comwrote:
8<--------------------------------
#loop through patterns list and find/replace data
for o, r in patterns:
data = data.replace(o, r)
print "Replaced %s with %s" % (o, r)
f.write(data)
f.close()

This results in an empty file. All of the modes I've tried either
produce an empty file or append the data onto the end of the file. How
I would take a hard look at what the find and replace does - it acts as if you
are replacing
*everything* with *nothing*....

- Hendrik

Nov 4 '06 #5
erikcw wrote:
To make it write over the data, I ended up adding, which seems to work
fine.

f = open('_i_define s.php', 'w+')
that doesn't work; you need to use "r+" if you want to keep the original
contents.

"w+" means truncate first, update then:
>>f = open("foo.txt", "r")
f.read()
'hello\n'
>>f.close()
>>f = open("foo.txt", "r+")
f.read()
'hello\n'
>>f.close()
>>f = open("foo.txt", "w+")
f.read()
''

the standard approach when updating text files is to create a *new*
file, though:

fi = open(infile)
fo = open(infile + ".tmp", "w")

filter fi to fo

fo.close()
fi.close()

if os.path.exists( infile + ".bak")
os.remove(infil e + ".bak")
os.rename(infil e, infile + ".bak")
os.rename(infil e + ".tmp", infile)

this leaves the old file around with a .bak extension, which is nice
if something goes wrong during filtering.

</F>

Nov 4 '06 #6

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

Similar topics

5
10142
by: simon place | last post by:
is the code below meant to produce rubbish?, i had expected an exception. f=file('readme.txt','w') f.write(' ') f.read() ( PythonWin 2.3 (#46, Jul 29 2003, 18:54:32) on win32. ) I got this while experimenting, trying to figure out the file objects modes,
0
1335
by: pxlpluker | last post by:
What exactly does the underlined text mean. w & a obviously mean you are going to update the file. So what does the + mean on w+ & a+ mean? Also please could someone explain w+ truncating the file. I may just be dense so please be patient :) ------------------------------------------------------------------------- file( filename ] )
8
9859
by: Brandon McCombs | last post by:
This may be the wrong group but I didn't see anything for VC++ so I'm trying here. I have a C++ book by Deitel and Deitel that says I can use fstream File("data.dat", ios::in | ios::out | ios::binary) to declare a file object with read/write modes turned on for working with binary data. I've tried this and my file is not created. The only time it is created is when I specify ifstream or ofstream but not fstream. I've tried removing the...
6
2066
by: Jakob Bieling | last post by:
Hi, I was wondering why there are file access modes, which you have to specify when opening the file. I am specifically talking about the 'read', 'read-write' and 'write' distinction. As far as I can tell, it only makes sure, you (the programmer) do not accidently write to it when you opened it for reading. To me, this seems like another one of those things that just make life harder. I am asking this, because I am writing a wrapper...
4
9844
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile = tmpfile(); /* write into tmpFile */ ...
68
5262
by: vim | last post by:
hello everybody Plz tell the differance between binary file and ascii file............... Thanks in advance vim
13
11156
by: George | last post by:
Hi, I am re-writing part of my application using C#. This application starts another process which execute a "legacy" program. This legacy program writes to a log file and before it ends, it writes a specific string to the log file. My original program (MKS Toolkit shell program) which keeps running "grep" checking the "exit string" on the "log files". There are no file sharing problem.
0
1720
grassh0pp3r
by: grassh0pp3r | last post by:
Hello, I'm trying to make a very simple comments page on my site using PHP and am having problems somewhere. I am very new to PHP. I was able to create one that works with comments appended, but I want the latest comment to be on top, and that's where I'm running into trouble. Since I know very little about PHP, I thought I was clever in what I came up with. I think it can work if I get the coding right. Let me know if my logic is wrong. I'm...
10
22755
by: rory | last post by:
I can't seem to append a string to the end of a binary file. I'm using the following code: fstream outFile("test.exe", ios::in | ios::out | ios::binary | ios::ate | ios::app) outFile.write("teststring", 10); outFile.close(); If I leave out the ios::ate and ios::app modes my string is written to the start of the file as I'd expect but I want to write the data to
0
9515
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
10207
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
10155
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
9995
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
9029
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...
0
6776
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
5431
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
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3718
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.