FileNotFoundError in opening txt file with python - 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:

Related

File Opening - Script still finds file in cwd even when absolute path specified

I have looked at How to open a list of files in Python This problem similar but not covered.
path = "C:\\test\\test5\\"
files = os.listdir(path)
fileNames = []
for f in files:
fileNames.append(f)
for fileName in fileNames:
pathFileName = path + fileName
print(f"This is the path: {pathFileName}")
fin = open(pathFileName, 'rt')
texts = []
with open(fileName) as file_in:
# read file text lines into an array
for text in file_in:
texts.append(text)
for text in texts:
print(text)
The file aaaatest.txt is in C:\test\test5 The output is:
This is the path: C:\test\test5\aaaatest.txt
Traceback (most recent call last):
File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'aaaatest.txt'
So here's the point. If I take a copy of aaaatest.txt (leaving original where it is) and put it in the current working directory. Running the script again I get:
This is the path: C:\test\test5\aaaatest.txt
A triple AAA test
This is the path: C:\test\test5\AALTONEN-ALLAN_PENCARROW_PAGE_1.txt
Traceback (most recent call last):
File "c:\Users\david\source\repos\python-street-spell\diffLibFieldFix.py", line 30, in <module>
with open(fileName) as file_in:
FileNotFoundError: [Errno 2] No such file or directory: 'AALTONEN-ALLAN_PENCARROW_PAGE_1.txt'
The file aaaatest.txt is opened and the single line of text, contained in it, is outputted. Following this an attempt is made to open the next file of C:\test\test5 where the same error occurs again.
Seems to me that while the path is saying C:\test\test5 the file is only being read from the cwd?

I'm trying to read in a csv file in pycharm that I downloaded on my mac and when I run my code it says no such file exists

#import necessary modules
import csv
with open ("C:/iCloud Drive/Desktop/Python/o.csv") as f:
data = csv.reader(f)
for row in data:
print(row)
Heres the error message
Traceback (most recent call last):
File "/Users/noahhenninger/PycharmProjects/Refactoring/main.py", line 3, in <module>
with open ("C:/iCloud Drive/Desktop/Python/o.csv") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/iCloud Drive/Desktop/Python/o.csv'
I tried adding more specific info about the location of the file but that didn't seem to work.

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)

Python 3 SublimeText 3 with open() resulting in FileNotFoundError

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.

How to turn a comma seperated value TXT into a CSV for machine learning

How do I turn this format of TXT file into a CSV file?
Date,Open,high,low,close
1/1/2017,1,2,1,2
1/2/2017,2,3,2,3
1/3/2017,3,4,3,4
I am sure you can understand? It already has the comma -eparated values.
I tried using numpy.
>>> import numpy as np
>>> table = np.genfromtxt("171028 A.txt", comments="%")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1551, in genfromtxt
fhd = iter(np.lib._datasource.open(fname, 'rb'))
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 151, in open
return ds.open(path, mode)
File "C:\Users\Smith\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 501, in open
raise IOError("%s not found." % path)
OSError: 171028 A.txt not found.
I have (S&P) 500 txt files to do this with.
You can use csv module. You can find more information here.
import csv
txt_file = 'mytext.txt'
csv_file = 'mycsv.csv'
in_txt = csv.reader(open(txt_file, "r"), delimiter=',')
out_csv = csv.writer(open(csv_file, 'w+'))
out_csv.writerows(in_txt)
Per #dclarke's comment, check the directory from which you run the code. As you coded the call, the file must be in that directory. When I have it there, the code runs without error (although the resulting table is a single line with four nan values). When I move the file elsewhere, I reproduce your error quite nicely.
Either move the file to be local, add a local link to the file, or change the file name in your program to use the proper path to the file (either relative or absolute).

Categories

Resources