Python -How to solve OSError: [Errno 22] Invalid argument [duplicate] - python

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 6 months ago.
I am learning about file objects in python but whenever i try to open file it shows the following error.
I have already checked that file is in same directory and it exists
this error occurs only if i name my file as test if i use any other name then it works fine
here's my CODE
f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
here's the ERROR
Traceback (most recent call last):
File "C:/Users/Tanishq/Desktop/question.py", line 1, in <module>
f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
OSError: [Errno 22] Invalid argument: 'C:\\Users\\Tanishq\\Desktop\\python
tutorials\test.txt'

Your issue is with backslashing characters like \T :
Try:
f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
Python uses \ to denote special characters. Therefore, the string you provided does not actually truly represent the correct filepath, since Python will interpret \Tanishq\ differently than the raw string itself. This is we we place the r in front of it. This lets Python know that we do indeed want to use the raw string and to treat \ as a normal character.

Related

Windows path with double backslash in Python [duplicate]

This question already has answers here:
What is different between makedirs and mkdir of os?
(3 answers)
Closed 7 months ago.
This seems to be very basic question but still I am confused. I have a windows path containing backslash, which to escape its special meaning I have used \\.
While I use print function get the path, gives me the actual return:
>>> print("C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources")
C:\Users\2.0Dev\8\F000B101\POD280-51\Resources
however, when the same is passed as an argument to two different functions in python, the behavior is different :
>>> rsrc_dir="C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources"
>>> os.path.isdir(rsrc_dir)
>>> False
>>> os.mkdir('C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 3] The system cannot find the path specified:'C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources'
Can someone please explain how the two functions interpret the same parameter. Also, how to return the formatted string same as the print function.
Much Thanks.
os.mkdir does not create intermediate catalogs, so this:
os.mkdir('C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources')
would fail if not
os.path.exists('C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51')
use os.makedirs if you want recursive directory creation. Note that you might use os.path.join which will use separator appriopiate to system at which it runs, in your case usage would be:
rsrc_dir=os.path.join("C:\\","Users","2.0Dev","8","F000B101","POD280-51","Resources")

How to solve the error in writing to a text file [duplicate]

This question already has answers here:
How can I create files on Windows with embedded slashes, using Python?
(3 answers)
Closed 2 years ago.
When I run the following code, instead of creating a text file in my working directory with the name '03/08/2020.txt', it generates an error FileNotFoundError: [Errno 2] No such file or directory: '03/08/2020.txt'. As far as I think, it is just because of the slashes.
But anyhow, I want to create a text file with slashes because this thing is a part of a large code and I have to work with dates (for attendance purposes).
dates = ['03/08/2020', '1', '2', '3']
def test(alist):
myfile = open(alist[0])+'.txt', 'w')
for i in alist:
myfile.write(f"{i}\n")
myfile.close()
test(dates)
is there a way yo handle this issue?
As jdaz said, you can instead use "03-08-2020.txt"
This is because on windows, you can't add to the following characters to your file names:
\ / : * ? " < > |
If you try to rename a file with one of those characters, you'll see a message saying you can't do so.

python misreading filepath name [duplicate]

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 want to iterate over a number of files in the L: drive on my computer in a folder called 11109. This is my script:
for filename in os.listdir('L:\11109'):
print(filename.split('-')[1])
However the error message comes back as :
File "L:/OMIZ/rando.py", line 12, in <module>
for filename in os.listdir('L:\11109'):
FileNotFoundError: [WinError 3] The system cannot find the path specified:
'L:I09'
Its reading the L:\ 11109 fine but the error message said the path specified is L:I09?
You need to use raw strings or escape the backslash, otherwise \111 is resolved to I:
a = 'L:\11109'
print(a) # shows that indeed 'L:I09'
b = r'L:\11109'
print(b) # prints 'L:\11109'
c = 'L:\\11109' # will be understood correctly by open()
To solve this you can do like this
for filename in os.listdir('L:/11109'):
print(filename.split('-')[1])

How can str.translate from Python 2, only removing characters, be made to work in Python 3? [duplicate]

This question already has answers here:
str.translate gives TypeError - Translate takes one argument (2 given), worked in Python 2
(4 answers)
Translate function in Python 3 [duplicate]
(4 answers)
Closed 5 years ago.
This is an assignment that needs to change the name of the file within a certain folder, however, it doesn't change the name after all. Can anyone help?
import os
def rename_files():
file_list = os.listdir(r"C:\Users\Downloads\prank")
saved_path = os.getcwd()
print("Current Working Directory is " +saved_path)
os.chdir(r"C:\Users\Downloads\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename_files()
result:
Traceback (most recent call last):
File "C:\Users\Downloads\prank\rename_files.py", line 10, in <module>
rename_files()
File "C:\Users\Downloads\prank\rename_files.py", line 8, in rename_files
os.rename(file_name, file_name.translate(None, '0123456789'))
TypeError: translate() takes exactly one argument (2 given)
This code works in Python 2, but does not work in Python 3. How can it be made to work in Python 3.6, I only need to delete characters.
You are confusing the Python 2 str.translate() method with the Python 3 version (which is really the same as unicode.tranlate() in Python 2).
You can use the str.maketrans() static method to create a translation map; pass your string of digits to be removed in as the third argument to that function:
file_name.translate(str.maketrans('', '', '0123456789'))
Better still, store the result of str.maketrans() outside of the loop, and re-use it:
no_digits = str.maketrans('', '', '0123456789')
for file_name in file_list:
os.rename(file_name, file_name.translate(no_digits))

how to create empty file in python [duplicate]

This question already has answers here:
Create empty file using python [duplicate]
(2 answers)
Closed 5 years ago.
I would like to create an empty file in Python. But I have difficulty creating one..Below is the Python code I used to create but it gives me error:
gdsfile = "/home/hha/temp.gds"
if not (os.path.isfile(gdsfile)):
os.system(touch gdsfile)
Error I got:
File "/home/hha/bin/test.py", line 29
os.system(touch gdsfile)
^
SyntaxError: invalid syntax
But from the command line, I am able to create new file using: touch
Thank you very much for your help
Howard
First you have a syntax error because os.system() expects a string argument and you have not provided one. This will fix your code:
os.system('touch {}'.format(gdsfile))
which constructs a string and passes it to os.system().
But a better way (in Python >= 3.3) is to simply open the file using the open() builtin:
gdsfile = "/home/hha/temp.gds"
try:
open(gdsfile, 'x')
except FileExistsError:
pass
This specifies mode x which means exclusive creation - the operation will fail if the file already exists, but create it if it does not.
This is safer than using os.path.isfile() followed by open() because it avoids the potential race condition where the file might be created by another process in between the check and the create.
If you are using Python 2, or an earlier version of Python 3, you can use os.open() to open the file with the exclusive flag.
import os
import errno
gdsfile = "/home/hha/temp.gds"
try:
os.close(os.open(gdsfile, os.O_CREAT|os.O_EXCL))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise

Categories

Resources