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')
Related
I'm trying to replace '\' with '\\', but its not working as i thought.
I tried using f.replace('\','\\'), but it is giving error like unexpected character after line continuation character.
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.dcap' in file:
files.append(os.path.join(r, file))
for f in files:
print(f)
f.replace( '\' , '\\')
os.system("dcapgen.exe f")
Basically i want to run .exe file on all the .dcap files in the given directory(path). while printing f in files, its giving file path name like C:\Users\folder\a.dcap. but while giving os.system("dcapgen.exe f"), because f is representing C:\Users\folder\a.dcap and single backslash is not recognized by python, its throwing error like
Tracing file: f
failed.
The file can still be processed, but the total frame count may show as zero and an error message may be generated for the final frame.
Cannot open file: "f" (No such file or directory)
so, i want to replace single backslash with double one. And i tried using os.system("dcapgen.exe C:\\Users\\folder\\a.dcap") and its working fine.
I would suggest to solve the problem differently. First of all there is the built-in package glob, which gives you the opportunity to use the asterisk as wildcard character to filter for the files of a certain type. Secondly you do not have to replace the file separators.
CODE
import glob
import os
files = glob.glob("{}{}*.dcap".format(path, os.filesep)
for f in files:
print(f)
os.system("dcapgen.exe \"{}\"".format(f))
EXPLANATION
The backslash character is escaping everything. So when you write '\', '\\', it actually resolves to this string ', plus the invalid sequence \\'. This is the cause for the error regarding the line continuation.
If you want to use the value of a string variable in another string you have to use a formatted string. I would recommend to use str.format instead of the modulo operation because it is more safe in terms of mishaps. In the error message it says that the file name "f" cannot be resolved by the operating system. This does not mean value of f but the literal string "f" as file name.
f is a variable. To use a variable in a string yuu'll need string Interpolation
You could use %-formatting
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.dcap' in file:
files.append(os.path.join(r, file))
for f in files:
print(f)
f.replace( '\' , '\\')
os.system("dcapgen.exe %s" % f)
This is my
import os
filenames= os.listdir (".")
file = open("XML.txt", "w")
result = []
for filename in filenames:
result = "<capltestcase name =\""+filename+"\"\n"
file.write(result)
result = "title = \""+filename+"\"\n"
file.write(result)
result = "/>\n"
file.write(result)
file.close()
My Question /help needed
I want to add standard text ""
to the txt generated, but i cant add it, it says sytax errors can somebody help with code please.
2) how can i just copy foldernames from directory instead of file names , since with my code , it copies all file names in into txt.
Thank you frnds ..
file.write("\\")
use the escape () to write special characters
print("\\<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\\")
Rather than escaping all those double-quotes, why not embed your string inside single quotes instead? In Python (unlike many other languages) there is no difference between using single or double quotes, provided they are balanced (the same at each end).
If you need the backslashes in the text then use a raw string
file.write(r'"\<?xml version="1.0" encoding="iso-8859-1"?>\"')
That will preserve all the double-quotes and the back-slashes.
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.
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')
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()