Python coding error: "file doesn't exist" [duplicate] - python

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 years ago.
I have a text file named hsp.txt in C:\Python27\Lib\site-packages\visual\examples and used the following code.
def file():
file = open('hsp.txt', 'r')
col = []
data = file.readlines()
for i in range(1,len(data)-1):
col.append(int(float(data[i].split(',')[5])))
return col
def hist(col):
handspan = []
for i in range(11):
handspan.append(0)
for i in (col):
handspan[i] += 1
return handspan
col = file()
handspan = hist(col)
print(col)
print(handspan)
But when I run it it says that that the file doesn't exist.
Traceback (most recent call last):
File "Untitled", line 17
col = file()
File "Untitled", line 2, in file
file = open('hsp.txt', 'r')
IOError: [Errno 2] No such file or directory: 'hsp.txt'
How do I fix this?
Also how do I output the mean and variance?

Have you thought where your path leads to? You need to supply the complete path to the file.
opened_file = open("C:/Python27/Lib/site-packages/visual/examples/hsp.txt")
A couple other things:
Don't use file as a variable name. The system already uses that name.
Use a with statement. It's considered better practice.
with open("C:/Python27/Lib/site-packages/visual/examples/hsp.txt"):
# do something
When the with block ends, the file is automatically closed. In your code, the file is left open until the file function is closed (and hence saved) with the .close() method.

When your specifying just the following line
file = open('hsp.txt', 'r')
It is trying to use your current directory, that is where ever you launched python from. So if you, from a command prompt were at C:\temp and executed python test.py it woud look for your hsp.txt in C:\temp\hsp.txt. You should specify the full path when your not trying to load files from your current directory.
file = open(r'C:\Python27\Lib\site-packages\visual\examples\hsp.txt')

Related

Python how can I split file name without extension as glob gives weird path? [duplicate]

This question already has answers here:
How do I get the filename without the extension from a path in Python?
(31 answers)
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 5 months ago.
I am having this code where I am reading all the JSON files stored:
json_files = glob.glob('testproject/JSON/*.json', recursive=True)
print(json_files)
Now I am creating a UML diagram for which I am creating a new file and giving the same name as the JSON file which is loaded without the .json extension.
I have this code doing that for me:
for single_file in json_files:
with open(single_file, 'r') as f:
json_data = json.load(f)
name = single_file.split('.')
# From JSON, create GANTT Diagram
with open(name[0].split('/')[-1] + ".uml", "w") as f:
#some logic inside this part
When I run the code it gives me this error:
['testproject/JSON\\abc.json', 'testproject/JSON\\xyz.json']
Traceback (most recent call last):
File "c:\Project\testproject\extract.py", line 28, in <module>
with open(name[0].split('/')[-1] + ".uml", "w") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'JSON\\abc.uml'
as it can been seen that when i print the json_files variable the path is something like this testproject/JSON\abc.json and because of that the split is not working properly maybe. Can someone guide me here? Thanks in advance.
This worked
from pathlib import Path
for single_file in json_files:
with open(single_file, 'r') as f:
json_data = json.load(f)
name = single_file.split('.')
# From JSON, create GANTT Diagram
with open(Path(name[0]).stem + ".uml", "w") as f:
#some logic inside this part

Zipfile closed within context manager [duplicate]

This question already has answers here:
Python: prevent mixed tabs/spaces on module import
(1 answer)
Indentation Error in Python [duplicate]
(7 answers)
Closed 5 years ago.
The following code is confusing the mess out of me. I've got a zip file which I am opening in a context manager. I'm trying to extract the contents of this zip file to a temporary directory. However, when I execute this code block, it tells me that there was an "Attempt to read ZIP archive that was already closed". I find this very strange, as the zip file in question was opened in (with?) a context manager! I've inserted several print statements for calls to methods/properties associated with the object at hand. They return successfully.
Where have I gone wrong? Why does the file believe itself closed?
Any help would be appreciated!
(Edit) Please find the traceback below.
Also, is there a better way to check if a zipfile is in fact open? Other than checking if .fp is True/False?
if config.get('settings', 'new_quarter') == "Yes":
#This gets the latest zip file, by year and quarter
new_statements_path = os.path.join(config.get('cleaning', 'historic_dir'), 'sql_files')
for directory,dirnames, filenames in os.walk(new_statements_path):
zips = [f for f in filenames if ".zip" in f]
highest_quarter = max([z.split('Q')[1].split('.')[0] for z in zips])
print 'Targeting this quarter for initial tables: %s' % (highest_quarter)
for z in zips:
if 'sql_files' in f:
if z.split('Q')[1].split('.')[0] == highest_quarter:
with zipfile.ZipFile(os.path.join(directory,z), 'r') as zip_f:
print zip_f.fp
initial_tables = tempfile.mkdtemp()
print 'initial tables', initial_tables, os.path.exists(initial_tables)
#Ensure the file is read/write by the creator only
saved_umask = os.umask(0077)
try:
print zip_f.namelist()
print zip_f.fp
zip_f.printdir()
zip_f.extractall(path=initial_tables)
except:
print traceback.format_exc()
os.umask(saved_umask)
if os.path.exists(initial_tables) == True:
shutil.rmtree(initial_tables)
Traceback:
Traceback (most recent call last):
File "/Users/n/GitHub/s/s/s/extract/extract.py", line 60, in extract_process
zip_f.extractall(path=initial_tables)
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 1043, in extractall
self.extract(zipinfo, path, pwd)
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 1031, in extract
return self._extract_member(member, path, pwd)
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 1085, in _extract_member
with self.open(member, pwd=pwd) as source, \
File "/Users/n/anaconda/lib/python2.7/zipfile.py", line 946, in open
"Attempt to read ZIP archive that was already closed"
RuntimeError: Attempt to read ZIP archive that was already closed
(SECOND EDIT)
Here's the (reasonably) minimal & complete version. In this case, the code runs fine. Which makes sense, there's nothing fancy going on. What's interesting is I placed the full example (the one below) immediately above the previous example (above). The code below still executes just fine, but the code above still produces the same error. The only difference however is the new_statements_path variable. In the code above, this string comes from a config file. Surely, this isn't the root of the error. But I can't see any other differences.
import traceback
import os
import zipfile
import tempfile
import shutil
new_statements_path = '/Users/n/Official/sql_files'
for directory,dirnames, filenames in os.walk(new_statements_path):
zips = [f for f in filenames if ".zip" in f]
highest_quarter = max([z.split('Q')[1].split('.')[0] for z in zips])
print 'Targeting this Quarter for initial tables: %s' % (highest_quarter)
for z in zips:
if 'sql_files' in f:
if z.split('Q')[1].split('.')[0] == highest_quarter:
with zipfile.ZipFile(os.path.join(directory,z), 'r') as zip_f:
print zip_f.fp
initial_tables = tempfile.mkdtemp()
print 'initial tables', initial_tables, os.path.exists(initial_tables)
#Ensure the file is read/write by the creator only
saved_umask = os.umask(0077)
try:
print zip_f.namelist()
print zip_f.fp
zip_f.printdir()
zip_f.extractall(path=initial_tables)
except:
print traceback.format_exc()
os.umask(saved_umask)
if os.path.exists(initial_tables) == True:
shutil.rmtree(initial_tables)
if os.path.exists(initial_tables) == True:
shutil.rmtree(initial_tables)

Python file open from path containing numbers

i have the following problem during file open:
Using PyQt QFileDialog I get path for files from user which I would like to read it
def read_file(self):
self.t_file = (QFileDialog.getOpenFileNames(self, 'Select File', '','*.txt'))
Unfortunately I cannot open a file if the path has numbers in it:
Ex:
'E:\test\02_info\test.txt'
I tried
f1 = open(self.t_file,'r')
Could anyone help me to read files from such a path format?
Thank you in advance.
EDIT:
I get the following error:
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
f1 = open(self.t_file,'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'E:\test\x02_info\test.txt'
The problem is caused by your use of getOpenFileNames (which returns a list of files) instead of getOpenFileName (which returns a single file). You also seem to have converted the return value wrongly, but since you haven't shown the relevant code, I will just show you how it should be done (assuming you are using python2):
def read_file(self):
filename = QFileDialog.getOpenFileName(self, 'Select File', '','*.txt')
# convert to a python string
self.t_file = unicode(filename)

Using python to read text files and answer questions

I have this file animallog1.txt which contains information that i would like to use to answer questions using python. How would i import the file to python, which would latter be used
I tried
with open('animallog1.txt', 'r') as myfile
but this is not working and just outputs no such file or directory even though i am pretty sure it exists
animal_names, dates, locations = [], [], []
with open('animallog1.txt', 'r') as myfile:
for line in myfile:
animal_name, date, location = line.strip().split(':')
animal_names.append(animal_name)
dates.append(date)
locations.append(location)
print(animal_names)
print(dates)
print(locations)
so this is the code that i have. animallog1.txt is the name of the file that i want to use.
However my output is
Traceback (most recent call last):
File "None", line 3, in <module>
builtins.FileNotFoundError: [Errno 2] No such file or directory: 'animallog1.txt'
how can i fix this?
Make sure you path is corret or try this:
file = open("sample.txt")
sample.txt is present in the current path, in my ubuntu it works.
I would take a look at this. So modifying your code could be like:
f = open('animal data.txt', 'r+');
f.readline(); //Do this until you've read your questions
f.write('Answer to the questions')

How can I edit a plain text file in Python?

I've been trying to create a python script that edits a file, but if the file is not already there, it has an error like this:
Traceback (most recent call last):
File "openorcreatfile.py", line 56, in <module>
fileHandle = (pathToFile, 'w')
IOError: [Errno 2] No such file or directory: '/home/me/The_File.txt'
It works fine if the file exists. I've also tried this:
fileHandle = (pathToFile, 'w+')
But it comes up with the same error. Do I need to explicitly check if the file is there? If so, how do I create the file?
EDIT: Sorry, I realized the folder was missing. I'm an idiot.
The error says "No such file or directory."
Since you're trying to create a file, that must not be what's missing. So you need to create the /home/me/ directory.
See os.makedirs.
fo = open("myfile.txt", "wb")
fo.write('blah')
fo.close()
That's it, this will do the job.
myfile = open('test.txt','w')
myfile.write("This is my first text file written in python\n")
myfile.close()
To check if the file is there you can do:
import os.path
os.path.isfile(pathToFile)
so you can handle it, only if it exists:
if os.path.isfile(pathToFile):
fileHandle = (pathToFile, 'w')
else:
pass #or other thing
There are several ways to create a file in python, but if you want to create a text file, take a look at numpy.savetxt, which I think is one of the easiest and most effective ways
with open("filename.txt", "w") as f:
f.write("test")

Categories

Resources