'Can't write to file after calling pandas read_excel
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick |
