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')
Related
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.
I want to read a text file on windows from python. I've done this on a mac terminal a million times but have just started using windows. First thing is to open the file:
file = open("C:\users\lbryan05\documents\Training\python\Lynda\ch 2\words.txt", 'r')
, which gives the syntax error:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape
I gathered something weird is happening with \u so I tried putting an r in front of the path to double up all the backslashes:
file = open(r"C:\users\lbryan05\documents\Training\python\Lynda\ch 2\words.txt", 'r')
So from this I get that 'no such directory exists'. So I gather windows is stupid and hides file extensions so I just need to emit words.txt. After doing that I am surprised by the following error:
PermissionError: [Errno 13] Permission denied: "path".
, which just makes no sense to me as to why I wouldn't have permission to the file because I can certainly access it.
I'm executing python through windows powershell (and sublime).
If the file is not too big I suggest to store the file on that variable, then do the desired changes on python, and then save the entire file with the editted data, using 'w' parameter into the file.
Try this:
# Open file to read it, and store it in a var.
with open("C:\\users\\lbryan05\\documents\\Training\\python\\Lynda\\ch 2\\words.txt", 'r') as f:
file_content = f.read()
# Do something with that var, manipulate it like you want
file_content = file_content + "test"
# Open file to write on it, and write your manipulated var.
with open("C:\\users\\lbryan05\\documents\\Training\\python\\Lynda\\ch 2\\words.txt", 'w') as w:
w.write(file_content)
I went through couple answers on forum already but without any success.
I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs:
file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'
My code:
import csv
file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". Still doesn't work.
Completely new to Linux and just can't find why this isn't working.
Each reply appreciated!
You should'nt use '~' to specify the path of your directory but the full path instead. E.g. :
import csv
file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv'). E. g. :
import csv
file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)
The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion
Try using the full file path, something like this:
file = open("/home/[username]/Desktop/xyz/city.csv", "rb")
Usually ~ does not expand properly. I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix.
I am a beginner, writing a python script in which I need it to create a file that I can write information to. However, I am having problems getting it to create a new, not previously existing file.
for example, I have:
file = open(coordinates.kml, 'w')
which it proceeds to tell me:
nameerror: name 'coordinates' is not defined.
Of course it isn't defined, I'm trying to make that file.
Everything I read on creating a new file says to take this route, but it simply will not allow me. What am I doing wrong?
I even tried to flat out define it...
file = coordinates.kml
file_open = open(file, 'w')
... and essentially got the same result.
You need to pass coordinates.kml as a string, so place them in quotes (single or double is fine).
file = open("coordinates.kml", "w")
In addition to the above answer,
If you want to create a file in the same path, then no problem or else you need to specify the path as well in the quotes.
But surely opening a file with read permission will throw an error as you are trying to access an nonexistent file.
To be future proof and independent of the platforms you can read and write files in binaries. For example if this is Python on Windows, there could be some alternations done to the end of line. Hence reading and writing in Binary mode should help, using switches "rb" and "wb"
file = open("coordinates.kml", "wb")
And also remember to close the file session, else can throw errors while re running the script.
I am attempting to print a line that contains a word from within a log file.
I have done some research and as of yet not found a good way to implement this.
I currently have this code:
FileInput = open(FILE, "r", encoding='utf-8')
for line in FileInput:
if "DATA: " in line:
print line
After looking around this seems be the way most people are doing it but I get the following error: TypeError: coercing to Unicode: need string or buffer, NoneType found.
I know the set length from "DATA:" and the line ends with a hexadecimal value of 0A.
Either your FILE variable does not contain a proper string (can we see the value of that? can you do "print(FILE)" before trying to open the file and paste here the result?), or the file is not encoded in a way that is compatible with utf-8. Try opening it in a good editor (like jEdit or Notepad++) and see what the editor tells you it is, then specify that encoding instead of utf.
It seems you need to use
import codecs
f = codecs.open(FILE, encoding='utf-8', mode='r')
Take a look here Unicode HOWTO
try this:
FileInput = open(FILE, "r")
for line in FileInput:
if "DATA: " in line:
print(line)