【发布时间】:2022-02-18 22:34:08
【问题描述】:
我在写入文件时遇到问题,我尝试了很多不同的写入文件的方法,但都没有奏效。我试图找出导致它的原因,因此使用了 f.open, write, close 来缩小问题的来源。我已将其范围缩小到此处的 pd.read_excel 文件:
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()
它成功写入 demofile1.txt 并关闭它。但随后无法写入 demofile2.txt 并出现以下错误:
f = open("demofile2.txt", "a")
FileNotFoundError: [Errno 2] No such file or directory: 'demofile2.txt'
很多类似的问题都在谈论使用绝对路径而不是相对路径,但这似乎不是问题,因为它可以很好地写入 demofile1.txt。
注意如果我将两个写入都移动到 pd.read_excel 行上方的演示文件,它将成功写入两者。
任何帮助将不胜感激。
【问题讨论】:
-
文件夹中是否已经存在文件
demofile2.txt? -
@Nick 当我运行脚本时,我删除了两个演示文件。如果我在两个演示文件都存在的情况下运行代码。它在第一个 f.close() 上失败,并带有“[Errno 9] Bad file descriptor”
-
@AlexisG 不幸的是它没有帮助。我只是尝试使用'a+'和'w'。仍然失败并出现同样的错误
标签: python python-3.x pandas