473,769 Members | 5,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File Handling Problems Python I/O

Hi,

I am having a problem with Python. I am new to Python as a programming
language, but I do have experience in other languages. I am
experiencing strange problems with File handling and wonder if anyone
else has seen this or knows what I am doing wrong. I am simply trying
to open a file for read and iterate through until the end of file. I am
able to do so without a problem, but here's the catch: The open
statement is only working on certain files. I open a simple text file
say file1.txt without any issues, but I change the open statement to
another text file and it error's out stating the file doesn't exist. I
know the code is correct because it worked for the other file. I have
tried both binary and ascii modes to no avail. Any idea why this is
happening? I am running Python 2.3.4 wxPython 2.5.3.1 and SPE as the
IDE on Win2k. Thanks

Josh

Jul 18 '05 #1
11 2864
I don't think we can help if you don't post some of your code.

Regards,
Arjen

Josh wrote:
Hi,

I am having a problem with Python. I am new to Python as a programming
language, but I do have experience in other languages. I am
experiencing strange problems with File handling and wonder if anyone
else has seen this or knows what I am doing wrong. I am simply trying
to open a file for read and iterate through until the end of file. I am
able to do so without a problem, but here's the catch: The open
statement is only working on certain files. I open a simple text file
say file1.txt without any issues, but I change the open statement to
another text file and it error's out stating the file doesn't exist. I
know the code is correct because it worked for the other file. I have
tried both binary and ascii modes to no avail. Any idea why this is
happening? I am running Python 2.3.4 wxPython 2.5.3.1 and SPE as the
IDE on Win2k. Thanks

Josh

Jul 18 '05 #2
Josh wrote:
I am having a problem with Python. I am new to Python as a programming
language, but I do have experience in other languages. I am
experiencing strange problems with File handling and wonder if anyone
else has seen this or knows what I am doing wrong. I am simply trying
to open a file for read and iterate through until the end of file. I am
able to do so without a problem, but here's the catch: The open
statement is only working on certain files. I open a simple text file
say file1.txt without any issues, but I change the open statement to
another text file and it error's out stating the file doesn't exist.


The usual rookie mistake here is to fail to recognize
that backslashes in strings are interpreted as special
escape sequences if they precede certain characters such
as "t" or "b". You probably have a path that looks like
this: "c:\temp\myfile .txt", right? The \t is actually
being converted into a TAB character.

You can use *forward* slashes in most cases in Windows,
except on the command line. The simplest fix is just
to convert your backslashes to forward slashes:
"c:/temp/myfile.txt"

Another approach, somewhat less desirable, is to use
"raw" strings instead, to prevent the escape sequences from
being recognized:
r"c:\temp\myfil e.txt"

Finally, and by far least desirable, use double-backslashes
to escape each backslash and in effect nullify the usual
escape handling:
"c:\\temp\\myfi le.txt"

Much less readable that way, but sometimes the right thing to do...

-Peter
Jul 18 '05 #3
He is the function where I am making the call. If I change the open
statment to another file, say "c:\test.tx t", a file I know exists, it
will error out stating the file does not exist. Thanks

Josh

def GetStartVars(se lf):
try:
DOWNFILE = open("c:\fixes. txt","r")
except IOError:
print "Failed to open file."
else:
counter = 1
while 1:
theline = DOWNFILE.readli ne()
if not theline:
break
print theline
counter = counter + 1
print counter
DOWNFILE.close( )

Jul 18 '05 #4
Peter,

Thank you for the rookie correction. That was my exact problem. I
changed the address to use forward slashes and it works perfect. I did
not know that a backslash had special meaning within a string, but now
I do! Thanks again

Josh

Jul 18 '05 #5
Josh wrote:
Peter,

Thank you for the rookie correction. That was my exact problem. I
changed the address to use forward slashes and it works perfect. I did
not know that a backslash had special meaning within a string, but now
I do! Thanks again

you may want to check "python gotchas" to avoid
other typical newbie errors:

<http://www.ferg.org/projects/python_gotchas. html>

HTH,
deelan

--
"Vedrai come ti tratteranno le mie TV"
Berlusconi a Follini (Luglio 2004)
Jul 18 '05 #6
Josh <Jo**********@g mail.com> wrote:
...
He is the function where I am making the call. If I change the open
statment to another file, say "c:\test.tx t", a file I know exists, it


Are you sure a file exist whose name is, c, colon, tab, e, s, t ...?

\t is an escape sequence and it means TAB (character of ascii code 9).

Try 'c:/test.txt' -- using normal slash instead the backslash -- and you
should be fine.

You mention you have some experience with other languages: if those
languages include C, or Java, or C++, and many others besides (all which
use backslashes for escape sequences in strings), you'd have exactly the
same issues.
Alex
Jul 18 '05 #7
You can use the os module to build path names in a platform-independent
manner. On my Linux box, I can type
BASE = '/'
import os
os.path.join(BA SE, 'foo', 'bar', 'baz') '/foo/bar/baz'

On a Windows machine, you get
BASE = 'C:'
import os
os.path.join(BA SE, 'foo', 'bar', 'baz')

'C:\\foo\\bar\\ baz'

This is a little more cumbersome that just typing the string, but using
os.path.join makes it easy to port your scripts to a new platform.
Check out http://docs.python.org/lib/module-os.path.html for more
information.
Cheers,

Michael

--
Michael Hartl
http://michaelhartl.org/

Jul 18 '05 #8
Sorry, the BASE variable should be 'C:\\' on Windows:
BASE = 'C:\\'
import os
os.path.join(BA SE, 'foo', 'bar', 'baz')

'C:\\foo\\bar\\ baz'

Jul 18 '05 #9
Micheal,

Thanks for the advice as the programming I am doing will be run on both
Windows and Linux based PC's, that being the main reason for my venture
into Python. I'm glad to see that people are willing to help out even
the newbie's.

Josh

Jul 18 '05 #10

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

Similar topics

5
10141
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,
7
6714
by: Eric Belanger | last post by:
Hi, Before posting I made sure I upgraded from 2.3.3 to 2.3.4, but the problem is still here. Ive created a little script which, at the end of it, deals with copying two files. All the script works fine except when its at the copy line(s). Nothing gets copied, it crashes at the first open() line. Before using open() I made it the lazy way first and wrote system("cp
9
3205
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is indeed also true for our language of choice, Python. Its file type allows some extraordinary convenient access like: for line in open("blah"): handle_line(line)
4
2447
by: Dirk Thierbach | last post by:
I am writing an Python 2.3 extension in C, and I would like to create events (Tk-style) from an external source. I use a library that already parses the events into a C structure. This library can also supply file ids for poll() or select() calls (all this is on Linux, BTW). What's the preferred way to doing this? Can I register my own event handlers to the Python runtime, including the file ids to poll/to do select on, as in Tcl/Tk? Or...
9
29232
by: wordsender | last post by:
Hey guys, I can't figure this one out, why is this simple script giving me problems? logfile=file(r'test.txt','w') logfile.write('datetime') test=logfile.readlines() When I run it I get the error message:
1
6509
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting" setting to be "E_ALL", notices are still not getting reported. The perms on my file are 664, with owner root and group root. The php.ini file is located at /usr/local/lib/php/php.ini. Any ideas why the setting does not seem to be having an effect? ...
19
4780
by: rmr531 | last post by:
First of all I am very new to c++ so please bear with me. I am trying to create a program that keeps an inventory of items. I am trying to use a struct to store a product name, purchase price, sell price, and a taxable flag (a Y/N char) and then write this all out to a file (preferably just a plain old text file) and then read it in later so that I can keep a running inventory. The problem that I am running into is when I write to the...
34
5368
by: Alexnb | last post by:
Gerhard Häring wrote: No, it didn't work, but it gave me some interesting feedback when I ran it in the shell. Heres what it told me: Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> os.startfile("C:\Documents and Settings\Alex\My Documents\My
2
3616
by: Felipe De Bene | last post by:
I'm having problems parsing an HTML file with the following syntax : <TABLE cellspacing=0 cellpadding=0 ALIGN=CENTER BORDER=1 width='100%'> <TH BGCOLOR='#c0c0c0' Width='3%'>User ID</TH> <TH Width='10%' BGCOLOR='#c0c0c0'>Name</TH><TH width='7%' BGCOLOR='#c0c0c0'>Date</TH> and so on.... whenever I feed the parser with such file I get the error :
0
9589
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
10049
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
9865
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
8873
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
7413
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
6675
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.