being a few weeks old coder,I am unable to make python read my file despite the code and .txt file being in the same folder
highest_score=0
result_f = open("results.text")
for line in result_f:
if float (line)>highest_score:
highest_score = float(line)
result_f.close()
print("the highest score:")
print(highest_score)
and result is
Traceback (most recent call last):
File "C:\Python33\-mu.py", line 2, in <module>
result_f = open("results.text")
FileNotFoundError: [Errno 2] No such file or directory: 'results.text'
Please help
Basically you are trying to open the file result.text. The error returned is that Python Idle cannot find that file. I notice that you mentioned a .txt file but in your code you try to open a .text file.
So I would suggest you to check wheter your file extension is .txt or .text and, in case, correct.
If the error still persists, try to give the full path to the open command. For example:
result_f = open("/Users/Joe/Desktop/results.text")
Both Windows and Mac OS give, somewhere when right-clicking on the file, the full path (among other information).
I faced a similar issue, where I was trying to read a file in idle but it couldn't find the path. What worked for me:
Enter the full path of the file with the extension
Instead of the native path writing style in windows i.e. (D:\python\sample.txt)
use (D:/python/sample.txt)
It worked out for me in Windows 7, IDLE 3.6.4 and also works on Windows 8
Related
This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 2 years ago.
I am somewhat new to programming, I don't like it that much but as it is school work I have to do it, good thing I find it interesting.
Here is my code, note I'm using VS code (some things are in french but that shouldn't affect anything):
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space vaders")
fond = pygame.image.load (testingfield.png)
and I get:
Traceback (most recent call last):
File "c:/Users/faver/Desktop/Space_Invaders-NSI/space_invaders_1.py", line 11, in <module>
fond = pygame.image.load ('testingfield.png')
FileNotFoundError: No such file or directory.
the file is indeed in the folder, and if I put fond = pygame.image.load ((r'C:\Users\faver\Desktop\Space_Invaders-NSI\testingfield.png'))it works perfectly, the problem now is that it'd be hard to actually send it since the other person would lack the folders I place there.
I've also tried import os a = os.path.lexists("/Users/suyeon/Documents/pythonWorkspace/pygame_basic/character.png") print(a) and it returned false, so I'm pretty much confused, I'd appreciate help if possible ^^'
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).
One solution is to change the working directory:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
An alternative solution is to find the absolute path.
If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the image filename. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
fondImgPath = os.path.join(sourceFileDir, 'testingfield.png')
fond = pygame.image.load(fondImgPath)
I just started learning Python this month with no prior coding knowledge. Before I could even get to practice coding, I was stuck with opening & importing files! To this end, I have no idea how to fix the problems as a newbie, so I will try to explain as best as I can.
1. Opening files.
Working directory is correct. The csv file was created with Geany on the Ubuntu operating system.
name=[]
age=[]
height=[]
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
csv file:
reader = csv.reader(csvfile, delimiter=’,’)
for row in reader:
name.append(row[0])
age.append(row[1])
height.append(row[2])
print("Done!")
**Error message:**
File "<ipython-input-3-f801fef0d65e>", line 5
with open(’/home/stephanie/chapter5exercise.csv’, encoding=’utf-8’,mode=’r’,newline=’’) as
^
SyntaxError: invalid character in identifier
2. Importing files
I downloaded a whatsapp chat text file for a coding exercise. It is stored in my Desktop environment. However, when I attempted to import it on Jupyter Notbook it didn't work.
I believe this is the problem, although I do not know how to work-around this:
the txt file's location as shown in my terminal:
/Users/Mac/Desktop
while the working directory as shown on Jupyter is:
/home/stephanie/Desktop
with open ("_chat.txt") as f:
data = f.readlines()
**error message:**
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-5-07cb5c381c47> in <module>
----> 1 with open ("_chat.txt") as f:
2 data = f.readlines()
FileNotFoundError: [Errno 2] No such file or directory: '_chat.txt'```
Any input or advice is greatly appreciated. Thanks very much in advance!
For the first error, try changing the apostrophes in the open line. For example, change ’/home/stephanie/chapter5exercise.csv’ to '/home/stephanie/chapter5exercise.csv'.
Apparently, the apostrophe (’) that you are using is not the correct one.
For the second error, try giving the entire path of the txt file.
Note: This was flagged as a potential duplicate of this, but the point of my question is that using textract doesn't work. I am looking either for (a) a way to get textract to work on windows 10 or (b) an alternate solution.
I am building a system that needs to read various types of files. I have set up pdfminer to read the .pdfs, and based on the process outlined here I installed textract, and I can now also read .docx files. However textract relies on antiword for reading .doc files and I cannot get this to work, even after following the directions here I could not find and install a working version of antiword. I do not have microsoft word installed on my machine, and I am running windows 10 with python 3.6.5. Is there any other way to read .doc files?
Here is the bug when running textract.process('d.doc') (ignore the first error, the file is definitely there):
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\textract\parsers\utils.py", line 84, in run
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "C:\ProgramData\Anaconda3\lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\ProgramData\Anaconda3\lib\site-packages\textract\parsers\__init__.py", line 77, in process
return parser.process(filename, encoding, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\textract\parsers\utils.py", line 46, in process
byte_string = self.extract(filename, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\textract\parsers\doc_parser.py", line 9, in extract
stdout, stderr = self.run(['antiword', filename])
File "C:\ProgramData\Anaconda3\lib\site-packages\textract\parsers\utils.py", line 91, in run
' '.join(args), 127, '', '',
textract.exceptions.ShellError: The command antiword d.doc failed with exit code 127
From the 'Windows installation problem' series: https://github.com/deanmalmgren/textract/issues/194#issuecomment-507243521
After following the steps to 'install' antiword, I was facing the same problem as yours.
Restarting windows after setting up the environment path variable entirely solved this exact error message for me. (This was the last error I was facing for handling .doc files with textract)
Installation instructions extracted from https://github.com/deanmalmgren/textract/issues/194#issuecomment-506065817
"Install Antiword
(I followed Reading .doc file in Python using antiword in Windows (also .docx))
Go to https://www.softpedia.com/get/Office-tools/Other-Office-Tools/Antiword.shtml
Extract to c:\antiword (yes it's required to be in the root directory)
Add location to path like we did tesseract-ocr [basically add c:\antiword to the system path (environment variable)]"
I was able to get part of the text using olefile, but olefile ultimately only handles bytes and does not handle the encoding of Word .doc files. The solution is to use LibreOffice, see my other question here
I am trying to follow the tutorials in the pyexiv2 tutorials page
But due to some unknown reasons, it refuses to run, and I thought of seeking some advice from you.
`#this is my code
import pyexiv2
metadata = pyexiv2.ImageMetadata('test.png')
metadata.read()`
when I try to run this code in the terminal, with the python interpreter, in the folder which contains the image, 'test.png', following error is given.
`Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pyexiv2/metadata.py", line 107,
in read
self.__image = self._instantiate_image(self.filename)
File "/usr/lib/python2.7/dist-packages/pyexiv2/metadata.py", line 74,
in
_instantiate_image
raise IOError(ENOENT, os.strerror(ENOENT), filename)
IOError: [Errno 2] No such file or directory: 'test.png'
`
This is my setup. I am running ubuntu 16.04LTS on virtual machine on a Mac book, with macOS sierra. Python version is 2.7.12.
I used this guide to install pyexiv2. when I inspect the /usr/local/lib folder, it shows that the libexiv2 is installed there.
What am I doing wrong here? and is there a better version of pyexiv2 to use?
I am fairly new to using python.:) and thanks in advance
This can be solved in two ways
1) Copy the file test.png in the same directory you have your python file with the code.
2) Provide a complete path. If, for example, you have test.png on your desktop, replace
metadata = pyexiv2.ImageMetadata('test.png')
with
metadata = pyexiv2.ImageMetadata('C:\\Users\\MYUSERPROFILENAME\\Desktop\\test.jpg')
where MYUSERPROFILENAME is your user profile. Hope this helps
Newb here to python/anaconda.
I'm trying to run a python script (and it reads other files local to its directory) which doesn't belong to the same directory as the Anaconda directory where I'm executing the python command there.
So I am trying to run a python script (lets say it resides in path B directory) from the Anaconda python (say path A directory). Within this script, there is a call to reading a local file so we have only the fileName.py and then the command prompt spits out this error:
C:\Users\usernameABC\Anaconda3>python C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py
Traceback (most recent call last):
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 165, in <module>
main()
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 130, in main
resp = ReadFemResp()
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 27, in ReadFemResp
dct = thinkstats2.ReadStataDct(dct_file)
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\thinkstats2.py", line 2646, in ReadStataDct
for line in open(dct_file, **options):
FileNotFoundError: [Errno 2] No such file or directory: '2002FemResp.dct'
I basically just want to run the script, whether its in Anaconda or wherever is the easiest or most natural that most experienced coders would. Please help! Thanks in advance for feedback!
You can change your current working directory using the
cd (change directory) command
You can also modify the script so that you can specify where the files are that you want to access. If you show us the script that you are running we may be able to help more.