python filename on windows - python

Disclaimer I have a similar thread started but I think it got too big and convoluted
In short this is the problem
import imghdr
import os.path
....
image_type = imghdr.what(os.path.normpath(filename))
fails with
IOError: [Errno 22] invalid mode ('rb') or filename: 'D:\\mysvn\\trunk\\Assets\\models\\character\\char1.jpg\r'
Where the aforementioned file does exist
Help? :D

There is a carriage return character \r at the end of the filename. That is not a valid character for a Windows filename, so I doubt the filename will work.
Use .rstrip('\r') to remove it:
image_type = imghdr.what(os.path.normpath(filename.rstrip('\r')))
.rstrip() removes characters from the end of a string, and only those in the set that you name.
Since this is a filename, any whitespace around the filename is probably incorrect, so a straight-up .strip() would work too:
image_type = imghdr.what(os.path.normpath(filename.strip()))
This would remove tabs, newlines, carriage returns and spaces from both the start and end of the string.

invalid mode ('rb') or filename: 'D:\\...\\char1.jpg\r'
^^
You have a trailing carriage return in the file path. Strip it first:
filename = filename.strip()

Related

How do I read a filepath from a text file using Python?

I am currently trying to write a simple python script that opens a folder or a list of folders using filepaths that I have written down on my text file.
import os
with open('filepaths.txt') as f:
[os.startfile(line) for line in f.readlines()]
My issue is that whenever I run this code, python reads the lines as its non-raw form. The backslashes are doubled, and there is a new line "\n" in every string.
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'D:\\Nitro\\Downloads\n'
I have attempted to solve this problem using repr() on the variable. Instead of removing the backslash, it was doubled even further.
import os
with open('filepaths.txt') as f:
[os.startfile(repr(line)) for line in f.readlines()]
FileNotFoundError: [WinError 2] The system cannot find the file specified: "'D:\\\\Nitro\\\\Downloads\\n'"
I have also attempted to use the string replace function to replace "\" with "". It did not work.
The readlines method reads the file correctly, with the trailing newline character in each line preserved. You just need to strip the newline character from the string before using it as a path name, which is typically done with the str.rstrip method:
for line in f: # no need to use the readlines method for iteration
os.startfile(line.rstrip())
The path name in the error message you included in the question contains double backslashes because it is displayed with the repr function, with backslashes escaped already, not because the path names are read incorrectly.

OSError: [Errno 22] Invalid argument, opening a file in python

I want to open a file and although I have given its address correctly, an error appears when I run the program.
This is my code:
file1 = open('‪‪C:\pronouns.txt‪', 'r')
This is the error:
OSError: [Errno 22] Invalid argument: '\u202a\u202aC:\\pronouns.txt\u202a'
I faced the same issue when I tried to copy filename directly from win10 file security properties dialog.
Here's Why is there an invisible U+202A at the start of my file name? helped me out, and maybe helpful to you as well.
The mysterious Unicode character "\u202a" is a formatting control character that means "LEFT-TO-RIGHT EMBEDDING" which is used to force text to be interpreted as left-to-right. However, it's invisible, if you try to copy the text out of the dialog box, the Unicode formatting control character comes along for a ride and may create all sorts of silent confusion.So, just input file path manually.
Forward and Backward slashes are always tricky. Can you try
file1 = open('‪‪C:/pronouns.txt‪', 'r')
file1 = open('‪‪C:\pronouns.txt‪', 'r').
rename the first character your file with capital
file1 = open('‪‪C:\Pronouns.txt‪', 'r')

Python doesn't create file if not existing

I cannot figure out how to create file that does not exist. I tried following, yet I get error that file does not exist.
Please guide.
f=open('c:\Lets_Create_Malware\output.txt', 'r+')
f=open('c:\Lets_Create_Malware\output.txt', 'w+')
f=open('c:\Lets_Create_Malware\output.txt', 'a+')
f=open('c:\Lets_Create_Malware\output.txt', 'r')
f=open('c:\Lets_Create_Malware\output.txt', 'w')
f=open('c:\Lets_Create_Malware\output.txt', 'a')
Use a double backslash:
f=open('c:\\Lets_Create_Malware\\output.txt', 'w+')
From the docs:
The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
Given the exact paths you've specificed, at least some of your examples ought to have worked (unless the c:\Lets_Create_Malware path doesn't exist, which would add to the confusion by causing all of your test cases to fail).
Backslashes aren't a problem here given your examples because the characters being modified aren't special:
f=open('c:\Lets_Create_Malware\output.txt', 'w')
works because \L and \o don't have special meanings and so are used literally (and the 'w' and 'a' flags will create the file if it's not already present).
However, another path:
f=open('c:\Lets_Create_Malware\badname.txt', 'w')
will fail:
IOError: [Errno 22] invalid mode ('w') or filename: 'c:\\Lets_Create_Malware\x08adname.txt'
because the \b part of that filename gets translated as the bell character (ctrl-b or \x08).
There are two ways to avoid this problem: either precede the string with the r raw string modifier (e.g., r'foo\bar') or ensure each backslash is escaped (\\). It's preferable to use os.path.join() from the os.path module for this purpose.

Python finding file path

if os.path.exists('D:\Python\New folder\'+f):
open(f+c, 'w')
The f is a character that changes in a loop. How do i add it to the rest of the 'D:\Python\New folder\' ? What i've done above makes the whole line highlighted as a comment.
You cannot use a \ backslash as the last character, as \' means use an actual quote character rather then the end of the string.
You should really use os.path.join() here and have Python join the path and the filename together, and use a raw string literal for the path so that the other \ characters don't form escape sequences (\n would be a newline, for example):
path = os.path.join(r'D:\Python\New folder', f)
if os.path.exists(path):
open(os.path.join(path, c), 'w')
os.path.join() will add the required \ path separators for you.
Use python os.path module
os.path.join
Try:
if os.path.exists('D:\Python\New folder\\'+f):
open(f+c, 'w')

How to execute Python code from file with a backslash character in it

I'm trying to run Python 3.3 code from a file with paths ("C:\Users\Documents\ect.") in it. When I try to run exec(commands), it returns this error:
tuple: ("(unicode error) 'unicodeescape' codec can't decode bytes in position ...
which I know is because of the single backslash character in the file paths, I know it works if it is backslashbackslash instead, but I don't know how to swap backslashbackslash for backslash. My code looks something like this:
filepath = HardDrive + "/Folder/" + UserName + "/file.txt"
file = open(filepath, 'r')
commands = file.read()
exec(commands)
The file simply has a command like this in it
os.remove("C:\Users\Documents\etc.")
The file path in the function in the file is returned automatically and I have no control over it.
Add a raw string r using str.replace to escape the filename inside the file:
with open("{}/Folder/{}/file.txt".format(HardDrive, UserName)) as f:
(exec(f.read().replace("C:\\",r"C:\\")))
Now the filename will look like 'C:\\Users\\Documents\\etc.'.
You also may need to remove that period:
exec(f.read().rstrip(".").replace("C:\\",r"C:\\"))
A simple
commands = commands.replace('\\', '/')
placed just before the exec(commands) would fix the problem if it's indeed all about the presence of backslashes (as it will turn each and every one of them into a forward slash).
Of course that's a problem if there are in the file also backslashes you want to keep as such (this simple code can't distinguish which ones you want to keep, which ones to replace!) but from your problem description this should not bother you in this case.
You can use r before your path, it will ignore all escape characters.
os.remove(r"C:\Users\Documents\etc.")
Like this.So,
file = open(r"filepath", 'r')
Beyond that, both Windows and Linux accepting / this for file paths. So you should use this. Not \, use this one /.
After your comment here;
file = open(r"{}".format(filepath), 'r')
Assume your variable is;
filepath = "c:\users\tom"
Put r before it and;
filepath = r"c:\users\tom"
Then use;
file = open(r"{}".format(filepath), 'r')
My final edit after you edited your question.
filepath = r"{}/Folder/{}/file.txt".format(HardDrive,UserName)
file = open(r"{}".format(filepath), 'r')

Categories

Resources