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.
Related
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')
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')
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 8 years ago.
I want to prompt a user for a number of random numbers to be generated and saved to a file. He gave us that part. The part we have to do is to open that file, convert the numbers into a list, then find the mean, standard deviation, etc. without using the easy built-in Python tools.
I've tried using open but it gives me invalid syntax (the file name I chose was "numbers" and it saved into "My Documents" automatically, so I tried open(numbers, 'r') and open(C:\name\MyDocuments\numbers, 'r') and neither one worked).
with open('C:/path/numbers.txt') as f:
lines = f.read().splitlines()
this will give you a list of values (strings) you had in your file, with newlines stripped.
also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.
Two ways to read file into list in python (note these are not either or) -
use of with - supported from python 2.5 and above
use of list comprehensions
1. use of with
This is the pythonic way of opening and reading files.
#Sample 1 - elucidating each step but not memory efficient
lines = []
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #or some other preprocessing
lines.append(line) #storing everything in memory!
#Sample 2 - a more pythonic and idiomatic way but still not memory efficient
with open("C:\name\MyDocuments\numbers") as file:
lines = [line.strip() for line in file]
#Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators.
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #preprocess line
doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.
the .strip() is used for each line of the file to remove \n newline character that each line might have. When the with ends, the file will be closed automatically for you. This is true even if an exception is raised inside of it.
2. use of list comprehension
This could be considered inefficient as the file descriptor might not be closed immediately. Could be a potential issue when this is called inside a function opening thousands of files.
data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]
Note that file closing is implementation dependent. Normally unused variables are garbage collected by python interpreter. In cPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.
f = open("file.txt")
lines = f.readlines()
Look over here. readlines() returns a list containing one line per element. Note that these lines contain the \n (newline-character) at the end of the line. You can strip off this newline-character by using the strip()-method. I.e. call lines[index].strip() in order to get the string without the newline character.
As joaquin noted, do not forget to f.close() the file.
Converting strint to integers is easy: int("12").
The pythonic way to read a file and put every lines in a list:
from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
lines = f.readlines()
Then, assuming that each lines contains a number,
numbers =[int(e.strip()) for e in lines]
You need to pass a filename string to open. There's an extra complication when the string has \ in it, because that's a special string escape character to Python. You can fix this by doubling up each as \\ or by putting a r in front of the string as follows: r'C:\name\MyDocuments\numbers'.
Edit: The edits to the question make it completely different from the original, and since none of them was from the original poster I'm not sure they're warrented. However it does point out one obvious thing that might have been overlooked, and that's how to add "My Documents" to a filename.
In an English version of Windows XP, My Documents is actually C:\Documents and Settings\name\My Documents. This means the open call should look like:
open(r"C:\Documents and Settings\name\My Documents\numbers", 'r')
I presume you're using XP because you call it My Documents - it changed in Vista and Windows 7. I don't know if there's an easy way to look this up automatically in Python.
hdl = open("C:/name/MyDocuments/numbers", 'r')
milist = hdl.readlines()
hdl.close()
To summarize a bit from what people have been saying:
f=open('data.txt', 'w') # will make a new file or erase a file of that name if it is present
f=open('data.txt', 'r') # will open a file as read-only
f=open('data.txt', 'a') # will open a file for appending (appended data goes to the end of the file)
If you wish have something in place similar to a try/catch
with open('data.txt') as f:
for line in f:
print line
I think #movieyoda code is probably what you should use however
If you have multiple numbers per line and you have multiple lines, you can read them in like this:
#!/usr/bin/env python
from os.path import dirname
with open(dirname(__file__) + '/data/path/filename.txt') as input_data:
input_list= [map(int,num.split()) for num in input_data.readlines()]