I'm trying to access a .txt file in Python and I can't figure out how to open the file. I ended up copying the contents into a list directly but I would like to know how to open a file for the future.
If I run this nothing prints. I think it's because Python is looking in the wrong folder/directory but I don't know how to change file paths.
sourcefile = open("CompletedDirectory.txt").read()
print(sourcefile)
The file CompletedDirectory.txt is probably empty.
If Python could not find the file, you would get a FileNotFoundError exception:
>>> sourcefile = open("CompletedDirectory.txt").read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'CompletedDirectory.txt'
Note that using read() in this way is not recommended. You're not closing the file properly. Use a context manager:
with open("CompletedDirectory.txt") as infile:
sourcefile = infile.read()
This will automatically close infile on leaving the with block.
You can get the current working directory:
import os
os.getcwd()
Then just concat it with the file container directory
os.path.join("targetDir", "fileName")
Related
I am trying to reach to the directory path of my edited text files with no success. This is my script:
contents = ["The document is only available for reading",
"Summary of family root work",
"Japan Culture: Long life"]
filenames = ["doc.txt", "report.txt", "representation.txt"]
for content, filename in zip(contents, filenames):
file = open(f"../Files/{filename}", 'w')
file.write(content)
The code generates the following error:
Traceback (most recent call last):
File "C:\Python\App1- To do list\venv\Bonus\bonus5.py", line 8, in <module>
file = open(f"../Files/{filename}", 'w')
FileNotFoundError: [Errno 2] No such file or directory: '../Files/doc.txt'
Note, the code written in a python file under different directory than the expected name "Files". The directory "Files" is existing but python don't interprets it. I expect to see the modified content for each text file. Please guys, how can I fix this problem?
So the problem is, I create a fprak.txt on my desktop, and I tried to use the following code to open it, but Error comes out. I use jupyter
Code:
file=open('fprak.txt')
print(file)
Error:
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-0d55e3a5adb7> in <module>
----> 1 file=open('fprak.txt')
2 print(file)
FileNotFoundError: [Errno 2] No such file or directory: 'fprak.txt'
Try using
file=open('~/Desktop/fprak.txt')
print(file)
Note that print(file) isn't going to print the file contents. Use print(file.read()) if you want to print the file contents.
I am trying to learn the file I/O in python, I am trying following code to generate a text file in D drive of my computer with the statements written in the code but the compilation fails saying that the file 'I want to create' is not available which is obvious. How to create the file then?
file = open(r'D:/pyflie/text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
and the error shown is
C:\Users\ssgu>python D:/pyfile/fw.py
Traceback (most recent call last):
File "D:/pyfile/fw.py", line 1, in <module>
file = open(r'D:/pyflie/text.txt',"w")
FileNotFoundError: [Errno 2] No such file or directory:
'D:/pyflie/text.txt'
You will get such an error if one of the specified directories does not exist. In this case, D:/pyflie/ does not exist yet, so it must be created beforehand. Then, your code should create and open the file normally. You can check upfront:
import os
if not os.path.exists(r"D:\pyflie"):
os.makedirs(r"D:\pyflie")
file = open(r'D:\pyflie\text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
Also, check for typos in the path name. Did you mean D:/pyfile/?
I'm running this script to loop over a directory of CSV files to run cross validation on.
for filename in os.listdir("/Users/name/PycharmProjects/Project/Data/Nod"):
k_fold(filename)
I get the error:
Traceback (most recent call last):
File "/path_of_cross_validation_file", line 28, in <module>
k_fold(filename)
File "/path_of_cross_validation_file", line 7, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'file_name.csv'
How do I iterate through all these files to split the data into training and testing files?
For reference, a file in Nod could look like this:
x,y,z
-1.3518261999999999,0.19841946999999999,0.058807577999999999
-1.5427636999999998,0.54079030000000006,-0.15981296
-1.4453497,0.04129998,0.046387657999999998
-1.4743793000000001,-0.064793080000000003,0.18315643000000001
It turns out I needed to use the glob module.
Here's the solution:
for filename in glob.iglob('Path_to_directory/*.csv'):
k_fold(filename)
I am trying to write to create and write to a text file. However, the error
Traceback (most recent call last):
File "/Users/muitprogram/PycharmProjects/untitled/histogramSet.py", line 207, in <module>
drinktrainfile = open(abs_file_path, "w")
IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'
shows up. There are other instances of this in Stack Overflow, however, none of these deal with creating and writing a new file. The directories all exist however- only the file is being created The code that does this is:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] # i.e. /path/to/dir/
rel_path = str(j) + "/train.txt" # HR/train.txt
abs_file_path = os.path.join(script_dir, rel_path) #/path/to/dir/HR/train.txt
drinktrainfile = open(abs_file_path, "w")
EDIT: train.txt shows up, except as a directory. How do I make it a text file?
The resource is actually a directory. It was very likely a mistake, as it is not likely that somebody would have created a directory by that name. First, remove that directory, and then try to create and open the file.
You can open the file with open('/Users/muitprogram/PycharmProjects/untitled/HR/train.txt', 'w'), assuming that the file does not already exist.