This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 7 months ago.
I am trying to read a text file on my hard drive via python with the following script:
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
But it is giving the following error:
IOError Traceback (most recent call last)
<ipython-input-2-4f422ec273ce> in <module>()
----> 1 fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
IOError: [Errno 2] No such file or directory: 'H:\\CloudandBigData\x0cinalproj\\BeautifulSoup\twitter.txt'
I also tried with other way:
with open('H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt', 'r') as f:
print f.read()
Ended up with the same error. The text file is present in the directory specified.
Replace
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
with
fileref = open(r"H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
Here, I have created a raw string (r""). This will cause things like "\t" to not be interpreted as a tab character.
Another way to do it without a raw string is
fileref = open("H:\\CloudandBigData\\finalproj\\BeautifulSoup\\twitter.txt","r")
This escapes the backslashes (i.e. "\\" => \).
An even better solution is to use the os module:
import os
filepath = os.path.join('H:', 'CloudandBigData', 'finalproj', 'BeautifulSoup', 'twitter.txt')
fileref = open(filepath, 'r')
This creates your path in an os-independent way so you don't have to worry about those things.
One last note... in general, I think you should use the with construct you mentioned in your question... I didn't in the answer for brevity.
I was encountering same problem. This problem resulted due to different file path notation Python.
For example, filepath in Windows reads with backward slash like: "D:\Python\Project\file.txt"
But Python reads file path with forward slash like: "D:/Python/Project/file.txt"
I used r"filepath.txt" and "os.path.join" and "os.path.abspath" to no relief. os library also generates file path in Windows notation. Then I just resorted to IDE notation.
You don't encounter this error if "file.txt" is located in same directory, as filename is appended to working directory.
PS: I am using Python 3.6 with Spyder IDE on Windows machine.
Related
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 15 days ago.
The requirement of code is I have to take the file path from the user in the console and perform some action on that file. Users can give paths in windows style or mac style. for the mac or Linux, the path code is working fine but for the windows path its give an error (because of ) how to handle this error as I can't use the 'r' string in that as it's coming from the user.
user_path = input('give text file path: ')
file = open(user_path, 'r')
words = file.read().split()
print('total number of words: ', len(words))
And if I provide path: C:\desktop\file.txt
its give error
Use C:\\desktop\\file.txt instead of C:\desktop\file.txt.
The error is due to the fact that python is recognizing '\f' in 'C:\desktop\file.txt' as the form feed escape sequence.
It can simply be resolved by using forward slash '/' instead of backslash while providing input.
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 2 years ago.
I have isolated a problematic part of my code and run it as 3 lines (see below), yet I still get this weird error where python tells me I used invalid argument, which looks different than the argument passed in. It apparently at random replaces one of my backslashes by double back slash (which shouldn't matter) and alters the name of the file i want opened.
Code:
fl = open("D:\test\sysi\temporary\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
Error:
OSError: [Errno 22] Invalid argument: 'D:\test\\sysi\temporary\x0ce_in.txt'
Anybody has encountered this? Any ideas what could be causing this or what could I try? (I have already deleted and re-created the file in question thinking it could be corrupted, didn't change anything)
I tested it and I needed to use double slash "\\" to use this without your error:
fl = open("D:\\test\\sysi\\temporary\\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
I believe it is because a single slash will be used as an escape character.
We do not know if your file is corrupted as you suspected in you question since the argument to "open" already was invalid. Your textfile was never opened before the error.
Now I only get, "[Errno 2] No such file or directory: 'D:\test\sysi\temporary\fe_in.txt'" because I did not place a file like yours in my file system, but if you have it the program should succeed.
try:
open(r"D:\test\sysi/temporary\fe_in.txt","r")
or
open(r"D:/test/sysi/temporary/fe_in.txt","r")
or
path = r"D:\test\sysi\temporary\fe_in.txt"
surely someone will work
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 22 days ago.
import os
import random
os.chdir("C:\Users\Mainuser\Desktop\Lab6")
#Am i supposed to have a os.chdir?
# I think this is what's giving the error
#how do i fix this?
def getDictionary():
result = []
f = open("pocket-dic.txt","r")
for line in f:
result = result + [ line.strip() ];
return result
def makeText(dict, words=50):
length = len(dict)
for i in range(words):
num = random.randrange(0,length)
words = dict[num]
print word,
if (i+1) % 7 == 0:
print
Python gives me an error saying it cannot find the path specified, when i clearly have a folder on my desktop with that name. It might be the os.chidr?? what am i doing wrong?
Backslash is a special character in Python strings, as it is in many other languages. There are lots of alternatives to fix this, starting with doubling the backslash:
"C:\\Users\\Mainuser\\Desktop\\Lab6"
using a raw string:
r"C:\Users\Mainuser\Desktop\Lab6"
or using os.path.join to construct your path instead:
os.path.join("c:", os.sep, "Users", "Mainuser", "Desktop", "Lab6")
os.path.join is the safest and most portable choice. As long as you have "c:" hardcoded in the path it's not really portable, but it's still the best practice and a good habit to develop.
With a tip of the hat to Python os.path.join on Windows for the correct way to produce c:\Users rather than c:Users.
Backslashes have special meaning inside Python strings. You either need to double them up or use a raw string: r"C:\Users\Mainuser\Desktop\Lab6" (note the r before the opening quote).
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
My problem is similar to Python's os.path choking on Hebrew filenames
however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).
I was doing data recovery for a client and copied over the files to my XP SP3 machine,
and some of the file names have "?" replacing/representing invalid characters.
I tried to use Python to os.rename the files since I know it has unicode support, however, when I tell python to rename the files, it seems it's unable to pass a valid file name back to the windows API.
i.e.:
>>> os.chdir(r'F:\recovery\My Music')
>>> os.listdir(u'.')
[u'Don?t Be Them.mp3', u'That?s A Soldier.mp3']
>>> blah=os.listdir(u'.')
>>> blah[0]
Don?t Be Them.mp3
>>> os.rename(blah[0],'dont be them.mp3')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
os.rename(blah[0],'dont be them.mp3')
WindowsError: [Error 123] The filename, directory name, or
volume label syntax is incorrect
I'm using Python 2.6, on Win XP SP3, with whatever encoding is standard XP behavior for US/English.
Is there a way to handle these renames without knowing the original language?
'?' is not valid character for filenames. That is the reason while your approach failed.
You may try to use DOS short filenames:
import win32api
filelist = win32api.FindFiles(r'F:/recovery/My Music/*.*')
# this will extract "short names" from WIN32_FIND_DATA structure
filelist = [i[9] if i[9] else i[8] for i in filelist]
# EXAMPLE:
# this should rename all files in 'filelist' to 1.mp3, 2.mp3, 3.mp3, ...
for (number, filename) in enumerate(filelist):
os.rename(filaname, '%d.mp3' % (number))
Try passing a unicode string:
os.rename(blah[0], u'dont be them.mp3')