Open an external file in python - python

x = open('Homework','r')
print(x.name)
x.close()
I got this error when I run the code.
File "C:/Users/LENOVO/Desktop/pythonhome/tobechanged.py", line 16, in <module>
x = open('Homework','r')
FileNotFoundError: [Errno 2] No such file or directory: 'Homework'
SO I tried to type the full path
x = open('C:\Users\LENOVO\Desktop\pythonhome','r')
print(x.name)
x.close()
I got an Unicode error.
btw I'm using windows.

As the comments mentioned, it's usually good to type out the full path to the file, because running a script in IDLE, for example, can cause Python to search for the file in a directory that you are not intending. The reason you got the Unicode error is because you are using a special character, the backslash (\) which starts something known as an escape sequence. Escape sequences allow coders to specify special characters, like the newline character: \n. You can read more about these in Python's docs here
You have to either use a raw string (a string preceded with r, like this r'C:\Users\...'), or escape these characters with double backslashes, like this: C:\\Users\\....
Additionally, you need to specify the extension for the Homework file, otherwise the file system won't be able to find the file you are referring to, resulting in the FileNotFoundError you encountered. As #tdelaney mentioned, these extensions may be hidden by default in Windows Explorer.
Also, the recommended way in Python to open files is using the with statement, as this handles closing the object for you. Here is a sample (assuming that the extension of the Homework file is .txt):
with open('C:\\Users\\LENOVO\\Desktop\\pythonhome\\Homework.txt', 'r') as x:
print(x.name)

It is because you are forgetting the extension to the file (the ending of it). For example, if you have a text file that is named Homework, you would include it in like this
open(r'Homework.txt','r')
For this example, it must be in the same directory as your script. If you wanted to open a file outside of your scripts directory, you would have to find the full path of it. Here is an example of the Homework.txt file in my downloads folder.
open(r'C:\Users\USER\Downloads\Homework.txt','r')
You can also see in this code I use an r infront of the path. This tells Python the expression is a raw string and escape sequences are not parsed.

Related

os.listdir works in console but fails in a script

My script uses os.listdir to get a list of directories to use later for batch analysis.
when running
mypath='//home//user//Documents//data'
datalist=os.listdir(mypath)
in console, I get the correct answer.
However, when I use the same code as a part of the script, python falls over on the datalist line
FileNotFoundError: [Errno 2] No such file or directory: '//home//user//Documents//data//'
Quoted from here:
The r'..' string modifier causes the '..' string to be interpreted
literally. That means, r'My\Path\Without\Escaping' will evaluate to
'My\Path\Without\Escaping' - without causing the backslash to escape
characters. The prior is equivalent to 'My\\Path\\Without\\Escaping'
string, but without the raw modifier.
And there is an explanation with a simple example at this link.
So use
mypath = r'\home\user\Documents\data'

Error opening a csv file in python from a specific directory

I am very new to python and I am not having much experience in programming.
I try to open a CSV file from a specific directory and I get error.
import csv
ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");
Error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");
IOError: [Errno 22] invalid mode ('rb') or filename: 'F:\\Study\\CEN\\Mini Project\\Data Sets\test.csv'
What to do ????
Use forward slashes:
ifile = open('F:/Study/CEN/Mini Project/Data Sets/test.csv', "rb");
Or at least escape your backslashes:
ifile = open('F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv', "rb");
Another option: use os.path.join:
out = os.path.abspath(os.path.join('path', 'test.csv'))
Your problem is here:
'F:\Study\CEN\Mini Project\Data Sets\test.csv'
^^
Because you did not use a raw string, Python thinks \t is supposed to mean a tab character.
You can see that in the error message, by the way: Notice how Python translated all the backslashes into double backslashes (which is how a literal backslash needs to be represented in a normal string) in all the places except the one where "backslash plus letter" actually meant something special?
Use
ifile = open(r'F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb")
(and remove the semicolons, you don't need them in Python) and it should work.
Your problem is with the "\t" AND a lack of exposure to various tools in the os.path package
The correct and easiest way to deal with this problem is to use os.path.normpath, combined with the string literal r, which ensures that backslashes are not interpreted as an escape character.
(Documentation on Lexical Analysis in python can be found here: https://docs.python.org/2/reference/lexical_analysis.html)
Open interactive python by typing "python" at the command line, and do the following to see that it's dead simple.
>>> import os
>>> path = r'F:\Study\CEN\Mini Project\Data Sets\test.csv'
>>> os.path.normpath(path)
'F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv'
normpath should be used when using hardcoded paths for scripts that may have to run on both dos and unix (eg OS X). It will ensure that the right kind of slashes are used for your particular environment
On a side note, if you are working with CSV files, you should use the petl library instead of the csv module. You'll save yourself a lot of time and hassle. Install it with pip install petl

how to escape single quote from string

This is my problem:
fpaths=os.listdir(ligand_names_list[0].replace("'", "\\'"))
OSError: [Errno 2] No such file or directory: "5-iodoindirubin-3\\'-oxime"
There is a file named 5-iodoindirubin-3'-oxime but I cannot make os.listdir() to find it. Here's another attempt I made inspired by this thread Adding backslashes without escaping [Python] :
fpaths=os.listdir(ligand_names_list[0].__ repr __())
OSError: [Errno 2] No such file or directory: '"5-iodoindirubin-3\'-oxime"'
The problem in this case is the leading single quotes which I don't know how to remove them. Any idea?
You don't have to escape anything; you only have to escape things when entering string literals into your code. Once the string has the right value, you can just use it as it is.
Is the file in the current directory, or in some other directory? (The current directory is the same directory your Python script is in, unless you've changed it.) If it's not in the current directory, that would explain why it's not being found.
(You say it's a file; I hope it is a directory, since you're calling os.listdir() on it...)

Cannot read in files

I have a small problem with reading in my file. My code:
import csv as csv
import numpy
with open("train_data.csv","rb") as training:
csv_file_object = csv.reader(training)
header = csv_file_object.next()
data = []
for row in csv_file_object:
data.append(row)
data = numpy.array(data)
I get the error no such file "train_data.csv", so I know the problem lies with the location. But whenever I specify the pad like this: open("C:\Desktop...etc) it doesn't work either. What am I doing wrong?
If you give the full file path, your script should work. Since it is not, it must be that you have escape characters in your path. To fix this, use a raw-string to specify the file path:
# Put an 'r' at the start of the string to make it a raw-string.
with open(r"C:\path\to\file\train_data.csv","rb") as training:
Raw strings do not process escape characters.
Also, just a technical fact, not giving the full file path causes Python to look for the file in the directory that the script is launched from. If it is not there, an error is thrown.
When you use open() and Windows you need to deal with the backslashes properly.
Option 1.) Use the raw string, this will be the string prefixed with an r.
open(r'C:\Users\Me\Desktop\train_data.csv')
Option 2.) Escape the backslashes
open('C:\\Users\\Me\\Desktop\\train_data.csv')
Option 3.) Use forward slashes
open('C:/Users/Me/Desktop/train_data.csv')
As for finding the file you are using, if you just do open('train_data.csv') it is looking in the directory you are running the python script from. So, if you are running it from C:\Users\Me\Desktop\, your train_data.csv needs to be on the desktop as well.

os.stat failing on file with funky characters

Using Python 2.6.5 on Windows XP, I'm processing a directory of files by calling os.stat on them to obtain their size. The script is failing when it reaches a particular file that happens to have non-ASCII characters embedded within the name. The exception being thrown is that os.stat couldn't find the file specified. I know the file is there because I can play in iTunes or VLC Media Player.
The name of the file in question is
1-02 Só Danço Samba (Jazz Samba).m4a
Just in case the characters aren't being displayed, the string is
'1-02 So\xb4 Danc\xb8o Samba (Jazz Samba).m4a'
Is there something I should or could be doing to make the name acceptable to os.stat? BTW, trying to open the file in python also fails for the same reason.
Try inserting the line # coding=UTF-8 at the top of your python file (only makes a difference for unicode in your script, as Philipp points out), and make sure you are storing the file names as unicode instead of str.
Tested with the following:
# coding=UTF-8
import os
fname = u'/temp/1-02 Só Danço Samba (Jazz Samba).m4a'
print(os.stat(fname))

Categories