【问题标题】:Can't write to file after calling pandas read_excel调用 pandas read_excel 后无法写入文件
【发布时间】: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


【解决方案1】:

我认为这可能与您尝试写入文件的方式有关。尝试从以下位置更改您的 open 和 write 行:

 f = open("demofile1.txt", "a")
 f.write("Now the file has more content!")
 f.close()

with open("demofile1.txt", "a") as f:
    f.write("Now the file has more content!")

使用context managers 是处理文件时的好习惯。来自文档here

上下文管理器允许您在需要时精确地分配和释放资源。

【讨论】:

  • 刚刚尝试过,不幸的是仍然遇到同样的错误
  • 在代码运行时是否打开了任何文本文件?
  • 不,全部关闭
  • 你在 Windows 上吗?
  • 是的,在 Windows 10 上(如果有任何更改,则在 azure 虚拟桌面上运行)
猜你喜欢
  • 2021-04-02
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多