I am trying to read a txt file(kept in another location) in python, but getting error.
FileNotFoundError
in ()
----> 1 employeeFile=open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt","r")
2 print(employeeFile.read())
3 employeeFile.close()
FileNotFoundError: [Errno 2] No such file or
directory:'C:\u202a/Users/xxxxxxxx/Desktop/python/files/employee.txt'
Code used:
employeeFile=open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt","r")
print(employeeFile.read())
employeeFile.close()
I tried using frontslash(/) and backslash(). But getting the same error.Please let me know what is missing in code.
I'm guessing you copy and pasted from a Windows property pane, switching backslashes to forward slashes manually. Problem is, the properties dialog shoves a Unicode LEFT-TO-RIGHT EMBEDDING character into the path so the display is consistent, even in locales with right-to-left languages (e.g. Arabic, Hebrew).
You can read more about this on Raymond Chen's blog, The Old New Thing. The solution is to delete that invisible character from your path string. Selecting everything from the initial " to the first forward slash, deleting it, then retyping "C:/, should do the trick.
As your error message suggests, there's a weird character between the colon and the forward slash (C:[some character]/). Other than that the code is fine.
employeeFile = open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt", "r")
You can copy paste this code and use it.
Related
There is no problem accessing the file but while reading I get the following error
from nltk.corpus.reader import WordListCorpusReader
reader= WordListCorpusReader("C:\\Users\samet\\nltk_data\\corpora\\bilgi\samet",
["politika.xls"])
a = reader.words()
print (a)
enter image description here
You'll want to make sure the file you're trying to load (politika.xls) is saved with utf-8 encoding. First I'll detail how I replicated your error, then I'll show an approach to solve it.
I was able to replicate your error as follows:
Create a new text document. "temp.txt"
Open it, add a few lines random text, save and close it.
Rename "temp.txt" to "temp.xls"
Open "temp.xls"
Save as.... "temp.xlsx"
Close file.
Rename "temp.xlsm" to "politika.xls"
Try running your code (with correction to path).
Receive your error: "UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 15-16: invalid continuation byte"
There may be a more straightforward approach, but from the above error condition, this worked to fix it:
Create a backup copy of "politika.xls"
Rename "politika.xls" to "old_politika.xls"
Create a new text file "politika.txt".
#Steps 3.1 - 3.4 may or may not be needed.
3.1. Open "politika.txt"
3.2. Save as...
3.3. Select Encoding >> (either ANSI or UTF-8 should work)
3.4. Save and close file.
Rename "politika.txt" to "politika.csv"
Open up "old_politika.xls"
Select and copy the data.
Open up "politika.csv"
Paste the data. Save and exit.
Rename "politika.csv" to "politika.xls"
Run your program. (See below for code / potential correction)
Also, you'll want to fix your dirrectory path. Make sure you use the excape character "\" for each "\" in the path. You were missing a "\" in front of " \samet" in 2 places. Corrected code below:
from nltk.corpus.reader import WordListCorpusReader
reader= WordListCorpusReader("C:\\Users\\samet\\nltk_data\\corpora\\bilgi\\samet",
["politika.xls"])
a = reader.words()
print (a)
I hope this helps.
Given this simple code, I receive faulty paths if the userfolder contains any special characters. For example the returned path is expected to be "C:\Users\Aoë\", but the ë is instead shown as a ‰ or a \u2030 depending on what is done with encoding. This then messes up the rest of my code because of attempts to write to nonexistent paths.
I ran into this problem trying to run kivy, but it seems to be happening globally.
from pathlib import Path
home = str(Path.home())
print(home)
I've spent quite some time, but haven't been able to reach a solution. This is with the latest python, x64 on windows with eclipse. No matter what I do, I cannot get python to handle special characters properly.
Try 'r' tag at the beginning, it ignores the special characters:
home = r'%s'%str(Path.home())
I started to learn pandas by following this tutorial:
https://github.com/jvns/pandas-cookbook
Right in the first chapter I try very elementary example of reading a csv file. The example goes like this:
import pandas as pd
broken_df = pd.read_csv("..\data\bikes.csv")
I get a lengthy error message, which ends with a line:
FileNotFoundError: File b'..\\data\x08ikes.csv' does not exist
So although I write 'bikes.csv', which I have in the correct folder, the program seems to be searching for a file called 'x08ikes.csv'. Could this be an encoding error? sys.getdefaultencoding() returns 'utf-8'.
I am using Anaconda3 for 64bit Windows, version 4.4.0. My browser is Brave. Any ideas what is going wrong here?
The backslash character '\' has special meaning; it tries to "escape" the next character. In this case '\b' is an escape character that does have a meaning. There are three ways around this:
Escape the escapes:
You can use the backslash to escape the next backslash, telling Python "this is just another character"
broken_df = pd.read_csv("..\\data\\bikes.csv")
Use a raw string:
Placing r at the beginning of a string tells Python to interpret everything in the string as-is
broken_df = pd.read_csv(r"..\data\bikes.csv")
Use forward slashes:
This is specific to file paths. You can trace the directory to you file using forward slashes instead of backslashes.
broken_df = pd.read_csv("../data/bikes.csv")
What you can do is, upload the bikes.csv in to the Jupyter Home "Files" tab. Open it and you may still see the message. Then go to File->New, and you may get a new blank file. Open the original bikes.csv in notepad, copy and paste the content in to the file in jupyter notebook. This may help to resolve it.
Then you can run the following code.
import pandas as pd
broken_df = pd.read_csv("..\data\bikes.csv")
I am trying to write code that takes 2 numbers in a text file and then divides them, showing the answer as a top heavy fraction. I have gotten the fractions part to work when I am inputting my own values in the program, but i cannot get the program to recognise the text file. I have tried putting them in the same directory and putting the full system path of the file, but nothing so far has worked. right now I am just trying to get the contents of the file to print.
with open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w') as f:
for line in f:
for word in line.split():
print(word)
I will then assign the 2 values to x and y, but I get this error:
Traceback (most recent call last):
File "C:\Python34\divider.py", line 2, in <module>
open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\\ProgramData\\Microsoft\\Windows\\Startmenu\\Programs\\Python 3.4\topheavy.txt'
open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\\ProgramData\\Microsoft\\Windows\\Startmenu\\Programs\\Python 3.4\topheavy.txt'
Two things:
When working with paths that contain backslashes, you either need to use two backslashes, or use the r'' form to prevent interpreting of escape sequences. For example, 'C:\\Program Files\\...' or r'C:\Program Files\...'.
Your error shows this: \\Startmenu\\. It appears that a space is missing between "Start" and "menu", despite the fact that the open line seems to have the right path.
Note: that the \topheavy.txt in your path is probably getting converted to <tab>opheavy.txt too. That's why there aren't two backslashes in front of it in the traceback.
You are using a "\" separator which is probably getting escaped somewhere (like that \t near the end. That's the Windows path separator, but also used as a string escape.
You can double up the "\" as "\". Easiest however is to prepend an r at the beginning to ignore .
r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt"
Skip the recommendation to use / instead, you are not on Unix and there is no reason Python can't accommodate Windows, as long as you remember to take care about "\" also being an escape. Using r' at start also allows you to copy/paste from the string into another program or vice-versa.
also, it wouldn't hurt to test in c:\temp or similar to avoid issues where you may have mistyped your path.
Last, but not least, you need to open in "r" read mode, as previously mentioned.
You should add one more "/" in the last "/" of path for example:
open('C:\Python34\book.csv') to open('C:\Python34\\\book.csv')
Reference
I had this same error appear when trying to read a large file in Python 3.5.4. To solve it, instead of reading the whole file into memory with .read(), I read each line one by one:
with open('big.txt') as f:
for i in f:
print(i)
Just as is written on the Python Documentation, the IOError Exception occurs:
Raised when an I/O operation (such as a print statement, the built-in
open() function or a method of a file object) fails for an I/O-related
reason, e.g., “file not found” or “disk full”.
Open with "r" (read) instead of "w" (write)
And startmenu in these two lines are different?? Try using a forward instead of a back slash. Python will convert the forward slash to the appropriate delimiter for the OS it is running on
open('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.4\topheavy.txt','w')
OSError: [Errno 22] Invalid argument:'C:\ProgramData\Microsoft\Windows\Startmenu\Programs\Python 3.4\topheavy.txt'
Replace every \ with \\ in file path
My issue, rather arbitrary, was I was writing a file using open(filename, "w").write(...), where filename is an invalid pathname or includes unexpected slashes.
For example, converting a datetime.datetime.today() into a datestring with slashes or colons (Windows) and writing to non-existing directories will result in this error.
Change:
open("../backup/2021/08/03 15:02:61.json", "w").write(data)
To:
open("../backup/2021-08-03 15-02-61.json", "w").write(backup)
As an example.
I'm new to Python and i'd like to build a script (Python 3) to test electronic modules and save log files.
I'd like to save the logfiles in the following format:
201410log.txt (yearmonthlog.txt)
This is done with the code:
import os
logfile=open(time.strftime('%Y%mlog.txt'), 'a')
logfile.write('This is a test\n\n\n')
This way, every month a new log file is created.
However, i'd like the logfiles to be in in a subdirectory (\logs).
I tried approaches like
logfile=open(time.strftime('\logs\%Y%mlog.txt'), 'a')
and similar things but i couldnt get any of them to work.
I searched trough other questions on stackoverflow (for example: Relative paths in Python ) and elsewhere in the internet, but i couldnt find the right solution.
Could someone point me in the right direction?
(sorry for any mistakes/spelling errors, i'm no native english speaker)
Remove the leading backslash. It makes the path absolute. Beside that, you need to escape a backslash.
logfile = open(time.strftime('logs\\%Y%mlog.txt'), 'a')
or use r'raw string literal':
logfile = open(time.strftime(r'logs\%Y%mlog.txt'), 'a')
For your current path string literal, it does not make problem. But paths like 'a\nb' will not work because \n is interpreted as newline instead of a literal backslash and n.