Hello to divine people with knowledge about Python.
I'm currently studying Python 3.4 and have encountered a problem.
About the load function, even when I used this function with the correct txtfile name an error appears.
results = []
with open('text.txt') as inputfile:
for line in inputfile:
results.append(line.strip().split(','))
Traceback (most recent call last):
File "F:/CSSE1001/Assignments/SunMum/030415.py", line 2, in <module>
with open('stations.txt') as inputfile:
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'
Looks like Python cannot find where the text.txt is..
Can someone please tell me how to set a directory of a function? Thank you.
You are probably looking for os.chdir(path). Alternatively, you could use os.path.join(path, *paths) to dynamically build the absolute path to hand over to the open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) function. It could also be that your text.txt file is not in the same directory as your 030415.py file (F:/CSSE1001/Assignments/SunMum).
Update: There are several ways you can load an entire file.
If you want to read all of a file as text, you can write data = open('text.txt', 'rt').read()
If you want to get all of a file's binary data, you can use data = open('text.txt', 'rb').read()
If you want the lines of a file, a simple way to get them would be with lines = tuple(open('text.txt', 'rt'))
If you want the lines without the newlines, you could type lines = open('text.txt', 'rt').read().split('\n')
If you want to process the lines efficiently while avoiding newlines, you could use for line in (line.strip('\n') for line in open('text.txt', 'rt')): to start a for loop.
If you are working with comma-separated values, you probably should look at the documentation for the csv module available with Python.
Related
I found this solution from stackoverflow but will i have to add this piece of code every time i write a code to perform read/write operations.
Or is there any long term solution available for this ?
import os
path = "E:\Python\learn"
os.chdir(path)
f = open('text.txt')
data = f.read()
print(data)
f.close()
I think you need a way to read same file multiple times in your python code. Use file.seek() to jump to a specific position in a file. However, think about whether it is really necessary to go through the file again. An Example for file.seek:
with open(name, 'r+') as file:
for line in file:
# Do Something with line
file.seek(0)
for line in file:
# Do Something with line, second time
Incase you want to re-iterate the file second time and don't want to open the file again, you can follow this syntax:
with open(name, 'r+') as file:
for line in file:
# Do Something with line
for line in file:
# Do Something with line, second time
I was having issues writing to file, I've tried a lot of different methods of writing to file and none have worked. I was trying to figure out what was causing it so have used f.open, write, close to narrow down where the issue is coming from. I've narrowed it down to the pd.read_excel file here:
import glob
import os
# Open most recent file (probably to be changed)
list_of_files = glob.glob(r'C:\Users\gamo0\Downloads\*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
f = open("demofile1.txt", "a")
f.write("Now the file has more content!")
f.close()
df = pd.read_excel(latest_file,sheet_name = 'People in your team',header=8)
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
It successfully writes to demofile1.txt and closes it. But then fails on writing to demofile2.txt with the following error:
f = open("demofile2.txt", "a")
FileNotFoundError: [Errno 2] No such file or directory: 'demofile2.txt'
A lot of similar issues talk about using absolute paths rather than relative, but it doesnt appear to be an issue with that as it can write to demofile1.txt fine.
N.B. if I move both write to demofiles above the pd.read_excel line, it will successfully write to both.
Any help would be appreciated.
I think it may be to do with how you are trying to write to the file. Try changing your open and write lines from:
f = open("demofile1.txt", "a")
f.write("Now the file has more content!")
f.close()
to
with open("demofile1.txt", "a") as f:
f.write("Now the file has more content!")
Using context managers is good practice when working with files. From the documentation here:
Context managers allow you to allocate and release resources precisely when you want to.
I am fairly new to Python and I am trying to learn how to read and write csv files.I am programming on my iPad using Pythonista and I’ve encountered a problem I cant seem to solve. I want to read a csv file of which I don’t know the directory because of the limited iOS File Management App. The csv file is in the same folder where my python file is.
I’ve found on google that I can find the absolute directory by using the following code:
import os
print(os.path.abspath("google_stock_data.csv"))
Which spits out:
/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv
Alright now on to my problem:
import csv
path = "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv"
file = open(path, newline= '')
reader = csv.reader(file)
header = next(reader)
data = [row for row in reader]
print(header)
print(data[0])
The upper code gives me the error:
FileNotFoundError: [Errno 2] No such file or directory: '/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/google_stock_data.csv'
I know that the file exists and the directory should be correct since I’ve also tried finding it with pathlib and it turned out to be the same.
So what seems to cause the problem?
Try using the with open() (read) syntax. I have something very similar and this works for me. Your path is correct.
with open(path, 'r', encoding='utf-8') as reader:
reader = csv.DictReader(reader)
for row in reader:
# ...do stuff
The problem lies within how I named my file. The name of the csv file that I wanted to open was called "google_stock_data.csv". Note that this is the filename and does not contain its file suffix at the end (which would be ".csv").
If you want to use file = open(...) you have to also add the file suffix at the end of the filename.
This means that this is how it should look like in my case:
file = open('google_stock_data.csv.csv', newline= '')
Finding the absolute path with print(os.path.abspath("enter_file_name")) is not needed if you have the file in the folder where your code is.If you do, for whatever reason, dont forget to add the file suffix at the end.
As for how to output anything from the file both my code and
with open(path, 'r', encoding='utf-8') as reader:
reader = csv.DictReader(reader)
for row in reader:
# ...do stuff
from #Michael M. work perfectly fine if you add .csv at the end of where you declare path.
I am trying to read a file in Python 3.8 that is has the extension ".input". However, it is meant to be read as a text file. I tried to connect to the file using this code:
file = open('file.input', 'r')
print("The contents of the file are:",file)
However, it does not output the contents of "file.input" (I wrote "Hello World" in there as a sample message).
You need to call read (or one of the other read methods) on the object returned by open.
with open('file.input', 'r') as f:
print(f.read())
The with keyword is helpful for making sure the file you open gets closed. For more information on file I/O in python you should really read the documentation here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files.
I have a text file (filenames.txt) which contains over 200 file paths:
/home/chethan/purpose1/script1.txt
/home/chethan/purpose2/script2.txt
/home/chethan/purpose3/script3.txt
/home/chethan/purpose4/script4.txt
Out of the multiple lines present in each of these files, each of them contain a line which is a filename like Reference.txt. My objective is to replace .txt in Reference.txt with .csv in every file. As a beginner of Python I referred to several questions in stackoverflow on similar cases and wrote the following code.
My code:
#! /usr/bin/python
#filename modify_hob.py
import fileinput
f = open('/home/chethan/filenames.txt', 'r')
for i in f.readlines():
for line in fileinput.FileInput(i.strip(),inplace=1):
line = line.replace("txt","csv"),
f.close()
f.close()
When I run my code, the contents of txt files (script1, script2..) mentioned above are wiped away, i.e., they won't be having a single line of text inside them! I am puzzled with this behavior and not able to find out a solution.
This should get you going (untested):
#! /usr/bin/python
#filename modify_hob.py
# Open the file with filenames list.
with open('filenames.txt') as list_f:
# Iterate over the lines, each line represents a file name.
for filename in list_f:
# Rewrite its content.
with open(filename) as f:
content = f.read()
with open(filename, 'w') as f:
f.write(content.replace('.txt', '.csv'))
In your code below, f is set to the open file object of filename.txt and
nothing else. That is what you are closing in both the last two lines.
Also, you are not writing anything back to the files, so you can't expect your
changes to be written back to the disk. (Unless the fileinput module does some
dark magic that I'm missing.)