This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 4 years ago.
I just started programming in python yesterday.
Ultimately I want to open a comma deliminated file and read its contents. I searched for related topics and tried using some of the code and am running into some errors.
Code:
def ReadTxtFile():
fname="c:\vba\lapseC2.csv"
#with open(fname) as f:
with open("c:\vba\lapseC2.csv", "r") as f:
content = f.readlines
you may also want to remove whitespace characters like \n at the end of each line
content = [x.strip() for x in content]
ReadTxtFile()
Error:
OSError: [Errno 22] Invalid argument: 'c:\x0bba\lapseC2.csv'
The backslash works as an escape symbol so if you want to insert it as a part of string, you should escape backslash itself:
fname="c:\\vba\\lapseC2.csv"
Another option is to use slashes, which seem to be supported by most popular operating systems:
fname="c:/vba/lapseC2.csv"
Related
This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 6 months ago.
Running below code in Azure Blobstorage concurrently is throwing
OS Error 22:Invalid argument pointing to f.close()
Is using Close() when using with open() creating OS error 22 issues?
Understand that Close() is not required but want to understand the root cause of OS error 22
*with open(openfilepath,"w+") as f:
f.write(writeFile )
f.close()*
Check the below possibilities and try.
1
If f.close() to be used you may try this by not using with
f = open(file_name, 'w+') # open file in write mode
f.write('write content')
f.close()
BUT
It is good practice to use with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes. once Python exits from the “with” block, the file is automatically closed.
So Please Remove f.close() and try.
with open(file_name, 'w+') as f :
f.write('write content')
Refer this for more info.
2
If above doen’t work check the filepath : It might be due to some invalid characters present in the file path name: It should not contain few special characters.
See if file path is for example : "dbfs:/mnt/data/output/file_name.xlsx"
Check if “/” is there before dbfs ( say /dbfs:/mnt/…).Try Removing if present.
NOTE:
``r+'': Open for reading and writing. The stream is positioned at
the beginning of the file.
``w+'': Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated. The stream is positioned at the
beginning of the file.
``a+'' : Open for reading and writing. The file is created if it does
not exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current end of
file, irrespective of any intervening fseek(3) or similar.
So try using other modes like r+ if w+ is not mandatory .See Python documentation
References:
1 , 2 ,3 , 4
Removing the F.close() fixed the issues when using With
This question already has an answer here:
Outputting Japanese Characters to a File using Python
(1 answer)
Closed 4 years ago.
How can I print Turkish?
open("save.txt", "w+").write("C:\Müzikler")
folder = open("save.txt", "r+").read()
os.listdir(folder)
OUTPUT:
FileNotFoundError: [WinError 3] The system cannot find the path specified:
C:\xfczikler'
For special characters (or in your case, accents) you need to encode with utf-8.
Do this with:
open("save.txt", 'w+', encoding='utf-8').write("C:\Müzikler")
This question already has answers here:
Reading Unicode file data with BOM chars in Python
(7 answers)
Closed 4 years ago.
I ran the following python code to open a CSV, and the first element had some extra characters in it that aren't present when I view the CSV in a text editor, say Notepad++.
priorities_file = open('priorities.txt', 'r')
print('Name of the file: ', priorities_file.name)
p = priorities_file.readlines()
print('Read Line: %s' % (p))
The output looked like this:
Name of the file: priorities.txt
Read Line: ['Autonomy\n', 'Travel\n',...
I understand the '\n' and how to remove that from each element, but I don't understand why there are the additional characters in front of the element ' Autonomy'. Can anyone tell me why this is? Bonus points for a way to remove those characters which I honestly couldn't find how to reproduce.
repr() would help. (on Python 3.X; use ascii() instead).
p = priorities_file.readlines()
print(repr(p))
My hunch is that the ecnoding in the csv file is not actually ASCII or UTF8?
UPDATE:
This should do the trick:
p = p.decode("utf-8-sig")
This question already has answers here:
Why do numbers in a string become "x0n" when a backslash precedes them?
(2 answers)
Closed 6 years ago.
I'm tring to open a file using the following code:
f=open('C:\Users\gabor\Desktop\NPI\test.csv', 'r')
reader=csv.reader(f)
for row in reader:
print row
Its returning an error:
IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\Users\\gabor\\Desktop\\NPI\test.csv'
I've change 'rb' to 'r' and left it out and I keep getting the same error.
Any suggestions on how to open the file?
I think you need double back-slash in your path. Or you can put "r" before the string as:
f=open(r'C:\Users\gabor\Desktop\NPI\test.csv', 'r').
This question already has answers here:
Line reading chokes on 0x1A
(2 answers)
Closed 4 years ago.
Newbie question. In Python 2.7.2., I have a problem reading text files which accidentally seem to contain some control characters. Specifically, the loop
for line in f
will cease without any warning or error as soon as it comes across a line containing the SUB character (ascii hex code 1a). When using f.readlines() the result is the same. Essentially, as far as Python is concerned, the file is finished as soon as the first SUB character is encountered, and the last value assigned line is the line up to that character.
Is there a way to read beyond such a character and/or to issue a warning when encountering one?
On Windows systems 0x1a is the End-of-File character. You'll need to open the file in binary mode in order to get past it:
f = open(filename, 'rb')
The downside is you will lose the line-oriented nature and have to split the lines yourself:
lines = f.read().split('\r\n') # assuming Windows line endings
Try opening the file in binary mode:
f = open(filename, 'rb')