Python 3 SublimeText 3 with open() resulting in FileNotFoundError - python

I'm trying to read this .txt file through Python (3.6.5), using SublimeText3 (3.1.1). learning_python.txt is in the same directory as my python program. I tried to make it an absolute filepath but getting FileNotFoundError either way. I also tried running it through Terminal with the same outcome. Is the code wrong?
filename = 'learning_python.txt'
print("--- Reading in the entire file:")
with open(filename) as f:
contents = f.read()
print(contents)
Traceback is:
--- Reading in the entire file:
Traceback (most recent call last):
File "C:\Users\sulli\Documents\Coding\Python Crash Course\Ch_10_Files_Exceptions\about_python.py", line 6, in <module>
with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/sulli/Documents/Coding/Python Crash Course/Ch_10_Files_Exceptions/learning_python.txt'

Looks like the issue here was I had named learning_python.txt file with the .txt at the end just like it is in the code. When I deleted the .txt on the text file itself, it worked in Python to find learning_python.txt. Python must have seen it as learning_python.txt.txt.

Related

Can't open file in the same directory

I was following a python tutorial about files and I couldn't open a text file while in the same directory as the python script. Any reason to this?
f = open("test.txt", "r")
print(f.name)
f.close()
Error message:
Traceback (most recent call last):
File "c:\Users\07gas\OneDrive\Documents\pyFileTest\ManipulatingFiles.py", line 1, in <module>
f = open("test.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
Here's a screenshot of proof of it being in the same directory:
The problem is "test.txt" is a relative file path and will be interpreted relative to whatever the current working directory (CWD) happens to be when the script is run. One simple solution is to use the predefined __file__ module attribute which is the pathname of the currently running script to obtain the (aka "parent") directory the script file is in and use that to obtain an absolute filepath the data file in the same folder.
You should also use the with statement to ensure the file gets closed automatically.
The code below shows how to do both of these things:
from pathlib import Path
filepath = Path(__file__).parent / "test.txt"
with open(filepath, "r") as f:
print(f.name)

Error message when using openpyxl.load_workbook() function

I have just started to learn programming and I am currently trying to read an excel file from IDLE. I'm following instruction from the book "Automate the Boring Stuff". I have successfully imported openpyxl, and thereafter, as instructed tried wb = openpyxl.load_workbook('example.xlsx') where I exchanged "example" to the actual name of the workbook. However, I get this error message:
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/reader/excel.py", line 117, in load_workbook
archive = ZipFile(filename, 'r', ZIP_DEFLATED) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/zipfile.py", line 1216, in __init__
self.fp = io.open(file, filemode) FileNotFoundError: [Errno 2] No such file or directory: 'jan.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
wb = openpyxl.load_workbook('jan.xlsx')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/openpyxl/reader/excel.py", line 145, in load_workbook
raise InvalidFileException(unicode(e))
openpyxl.exceptions.InvalidFileException: [Errno 2] No such file or directory: 'jan.xlsx'
I don't understand how to solve this.
This error message simply says that python can't locate the file. When you try to open a file 'jan.xlsx', it's trying to locate it in the base directory of your code in your IDE. So say your code is in a directory called /Users/username/PycharmProjects/myCode
(I'm assuming here you are on a Mac OS as the path to your python suggests...
but jan.xlsx is in /Users/username
Since that is 2 directories up from your code directory, you can do one of two things:
Write in the absolute path to the file:
wb = openpyxl.load_workbook('/Users/username/jan.xlsx')
Use a relative path that is relative to the base project directory. Two dots in a relative path means one level up from the current directory. So if the excel file is 2 levels up, you can do:
wb = openpyxl.load_workbook('../../jan.xlsx')

FileNotFoundError in opening txt file with python

I am trying to open a txt file for reading with this code:-
type_comments = [] #Declare an empty list
with open ('society6comments.txt', 'rt') as in_file: #Open file for reading of text data.
for line in in_file: #For each line of text store in a string variable named "line", and
type_comments.append(line.rstrip('\n')) #add that line to our list of lines.
Error:-
Error - Traceback (most recent call last):
File "c:/Users/sultan/python/society6/society6_promotion.py", line 6, in <module>
with open ('society6comments.txt', 'rt') as in_file:
FileNotFoundError: [Errno 2] No such file or directory: 'society6comments.txt'
I already have a file name with 'society6comments.txt' in the same directory has my script so why is it showing error?
The fact that the text file is in the same directory as your program does not make that directory the current working directory. Put the full path to the file in your open() call.
You can use os.path.dirname(__file__) to obtain the directory name of the script, and then join the file name you want:
import os
with open (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'society6comments.txt'), 'rt') as in_file:

IOError: [Errno 2] Python script to parse txt files

I'm starting a python script to parse a number of small text files in a folder. I need to retrieve particular information that will always be different (in this case hostname, model & serial number for a Cisco switch) and so can't use a regular expression. However I can easily find the line that contains the information. This is what I have so far:
import os
def parse_files(path):
for filename in os.listdir(path):
with open(filename,'r').read() as showfile:
for line in showfile:
if '#sh' in line:
hostname = line.split('#')[0]
if 'Model Number' in line:
model = line.split()[-1]
if 'System serial number' in line:
serial = line.split()[-1]
showfile.close()
path = raw_input("Please specify Show Files directory: ")
parse_files(path)
print hostname,model,serial
This, however, is returning:
Traceback (most recent call last):
File "inventory.py", line 17, in <module>
parse_files(path)
File "inventory.py", line 5, in parse_files
with open(filename,'r').read() as showfile:
IOError: [Errno 2] No such file or directory: 'Switch01-run.txt'
where 'Switch01-run.txt' is a file in the specified folder. I can't figure out where I'm taking a wrong turn.
The problem is that os.listdir() is returning the filenames from the directory, not the complete path to the file.
You need to do this instead:
with open(os.path.join(path,filename),'r') as showfile:
This fixes two issues - the IOerror, and the error you will get trying to read lines from a string.

Python 3.4.1: Can't Open and Read a local file

def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
data = Source_obj.read()
I am having trouble opening this file while located in a sub-directory directly underneath my Python file... is there a better way to open files from ANY directory on my computer?
FileNotFoundError: [Errno 2] No such file or directory: 'WebSource\\EXAMPLE SOURCE.htm'
I can't read from the file because I get the following error:
C:\python34\python.exe G:\Robot\test.py
Process started >>>
Traceback (most recent call last):
File "G:\Robot\test.py", line 118, in <module>
functION()
File "G:\Robot\test.py", line 64, in functION
data = Source_obj.read()
AttributeError: 'str' object has no attribute 'read'
<<< Process finished. (Exit code 1)
================ READY ================
BTW: The file to be read is just a source file from an HTML Chrome webpage.
EDIT
I'm looking for more help with the path and wondering why I get the first mentioned Traceback regarding the path
os.path.relpath() returns a string, not an open file object. You'll need to open a file first; use the open() function:
def functION():
Source_obj = path.relpath(r"WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as fileobj:
data = fileobj.read()
with here treats the file object as a context manager; when the indented codeblock under the statement is exited (either because the code completed or an exception occurred), the file object will automatically be closed.
Your Source_obj is just a string, not a file.
def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as f:
data = f.read()
By open()-ing it you can read from the file. Using the with context manager, the file will be properly closed for you when you leave that block of code.

Categories

Resources