Python File Read Error
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring python file open exceptions developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask io error in python Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join
I/o Error In Python
them; it only takes a minute: Sign up What is a good way to handle exceptions when trying to read a file in python? up vote 9 down vote favorite 2 I want to read a .csv file in
What Type Of Error Occurs When You Can't Open A File
python. I don't know if the file exists. My current solution is below. It feels sloppy to me because the two separate exception tests are awkwardly juxtaposed. Is there prettier way to do it? import csv fName = "aFile.csv" try: with open(fName, 'rb') as f: reader = csv.reader(f) for row in reader: pass #do stuff here except IOError: print "Could not read file:", fName python file-io exception-handling share|improve this question edited Apr 11 '11 at 21:08 asked Apr 11 python ioerror '11 at 20:51 CharlesHolbrow 1,05431621 add a comment| 4 Answers 4 active oldest votes up vote 6 down vote accepted I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that. So the answer is either: "Tim's way" or "No, you're doing it correctly.". Previous unhelpful answer to which all the comments refer: import os if os.path.exists(fName): with open(fName, 'rb') as f: try: # do stuff except : # whatever reader errors you care about # handle error share|improve this answer edited Apr 11 '11 at 21:23 answered Apr 11 '11 at 20:55 Josh Caswell 52.6k11103152 5 Just because a file exists doesn't mean that you can read it! –Gabe Apr 11 '11 at 20:59 1 This isn't perfect, because it is possible that the file gets deleted (e.g. by another process) between checking that it exists and trying to open it. –Liquid_Fire Apr 11 '11 at 20:59 1 It's also possible that fName could be the name of some file which, even if it sticks around, cannot be
Digest Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] I change my code and it runs on Python 3 now. f = open(rootdir+file, 'rb') data
An Exception Can Be In Python
= f.read().decode('utf8', 'ignore') Thank you very much. Sincerely, Dat. On Sat, Jul 28, 2012 syntax for generic except clause in python at 6:09 PM, Steven D'Aprano wrote: > Dat Huynh wrote: >> >> Dear all, >> >> I have is nested try block possible in python written a simple application by Python to read data from text >> files. >> >> Current I have both Python version 2.7.2 and Python 3.2.3 on my laptop. >> I don't know why it does http://stackoverflow.com/questions/5627425/what-is-a-good-way-to-handle-exceptions-when-trying-to-read-a-file-in-python not run on Python version 3 while it runs >> well on Python 2. > > > Python 2 is more forgiving of beginner errors when dealing with text and > bytes, but makes it harder to deal with text correctly. > > Python 3 makes it easier to deal with text correctly, but is less forgiving. > > When you read from a file in Python 2, it will give https://mail.python.org/pipermail/tutor/2012-July/090601.html you *something*, even if > it is the wrong thing. It will not give an decoding error, even if the text > you are reading is not valid text. It will just give you junk bytes, > sometimes known as moji-bake. > > Python 3 no longer does that. It tells you when there is a problem, so you > can fix it. > > > >> Could you please tell me how I can run it on python 3? >> Following is my Python code. >> >> ------------------------------ >> for subdir, dirs, files in os.walk(rootdir): >> for file in files: >> print("Processing [" +file +"]...\n" ) >> f = open(rootdir+file, 'r') >> data = f.read() >> f.close() >> print(data) >> ------------------------------ >> >> This is the error message: > > [...] > >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position >> 4980: ordinal not in range(128) > > > > This tells you that you are reading a non-ASCII file but haven't told Python > what encoding to use, so by default Python uses ASCII. > > Do you know what encoding the file is? > > Do you understand about Unicode text and bytes? If not, I suggest you read > this article: > > http://www.j
exceptions While a program is running, its data is in memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a http://www.greenteapress.com/thinkpython/thinkCSpy/html/chap11.html hard drive, floppy drive, or CD-ROM. When there are a large number of files, they http://www.diveintopython.net/file_handling/file_objects.html are often organized into directories (also called "folders"). Each file is identified by a unique name, or a combination of a file name and a directory name. By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to in python open it. When you're done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well. To open a file, you specify its name and indicate whether you want to error in python read or write. Opening a file creates a file object. In this example, the variable f refers to the new file object. >>> f = open("test.dat","w") >>> print f The open function takes two arguments. The first is the name of the file, and the second is the mode. Mode "w" means that we are opening the file for writing. If there is no file named test.dat, it will be created. If there already is one, it will be replaced by the file we are writing. When we print the file object, we see the name of the file, the mode, and the location of the object. To put data in the file we invoke the write method on the file object: >>> f.write("Now is the time") >>> f.write("to close the file") Closing the file tells the system that we are done writing and makes the file available for reading: >>> f.close() Now we can open the file again, this time for reading, and read the contents into a string. This time, the mode argument is "r" for reading: >>> f = open("test.dat","r") If we try to open a file that doesn't exist, we get an error: >>> f = open("test.cat","r") IOError: [Errno 2] No such file or directory: 'test.cat' Not surprisingly, the read method reads data from the file. With no ar
Handling I/O Errors 6.2.4. Writing to Files Python has a built-in function, open, for opening a file on disk. open returns a file object, which has methods and attributes for getting information about and manipulating the opened file. Example6.3.Opening a File>>> f = open("/music/_singles/kairo.mp3", "rb") >>> f >>> f.mode 'rb' >>> f.name '/music/_singles/kairo.mp3' The open method can take up to three parameters: a filename, a mode, and a buffering parameter. Only the first one, the filename, is required; the other two are optional. If not specified, the file is opened for reading in text mode. Here you are opening the file for reading in binary mode. (print open.__doc__ displays a great explanation of all the possible modes.) The open function returns an object (by now, this should not surprise you). A file object has several useful attributes. The mode attribute of a file object tells you in which mode the file was opened. The name attribute of a file object tells you the name of the file that the file object has open. 6.2.1.Reading Files After you open a file, the first thing you'll want to do is read from it, as shown in the next example. Example6.4.Reading a File >>> f >>> f.tell() 0 >>> f.seek(-128, 2) >>> f.tell() 7542909 >>> tagData = f.read(128) >>> tagData 'TAGKAIRO****THE BEST GOA ***DJ MARY-JANE*** Rave Mix 2000http://mp3.com/DJMARYJANE \037' >>> f.tell() 7543037 A file object maintains state about the file it has open. The tell method of a file object tells you your current position in the open file. Since you haven't done anything with this file yet, the current position is 0, which is the beginning of the file. The seek method of a file object moves to another position in the open file. The second parameter specifies what the first one means; 0 means move to an absolute position (counting from the start of the file), 1 means move to a relative position (counting from the current position), and 2 means move to a position relative to the end of the file. Since the MP3 tags you're looking for are stored at the end of th