CSV文件创建失败与路径问题:OSError[Errno9]如何解决?
解决CSV文件操作中的"Bad File Descriptor"及路径问题
报错信息
- CSV File cannot creat: Bad File Descriptor
- Failure: OSError: [Errno 9] Bad file descriptor
- Python can not find the path!!
相关代码
import pandas as pd import csv def read_csv_auto_header(file_path): # Öffnen der CSV-Datei und Lesen der Daten mit dem csv.reader # CSV-Datei in DataFrame lesen df = pd.read_csv(file_path, encoding='ISO-8859-1', sep=';') # Ersetzen von mehrstelligen Leerzeichen durch ein Leerzeichen df = df.replace('\s+', ' ', regex=True) df.to_csv(r'D:\Markus\00_Documents\20_Bildung\60_Self_Online_Study\60_Programmieren\Projekte\CreditKonto_analysing\neue_datei.csv',index=False,header=True) # Beispielverwendung file_path = 'Buchung.csv' # Ersetze 'Buchung.csv' durch deinen Dateipfad zur CSV-Datei read_csv_auto_header(file_path)
问题分析
报错核心是路径解析不规范、编码不统一或文件资源被占用,导致输入文件找不到、写入时触发文件描述符错误,和你推测的路径编码不一致方向吻合。
解决方案
1. 用绝对路径替代相对路径
相对路径'Buchung.csv'依赖程序运行的当前工作目录,一旦目录不匹配就会找不到文件。可以直接指定完整路径,或通过os模块转换为绝对路径:
import os # 转换为绝对路径 file_path = os.path.abspath('Buchung.csv') # 或直接写完整路径 file_path = r'C:\你的实际文件目录\Buchung.csv'
2. 确保输出目录存在并规范路径构建
如果输出目录不存在,写入操作会直接失败。用os模块提前创建目录,并用os.path.join构建路径,避免硬编码的格式错误:
output_dir = r'D:\Markus\00_Documents\20_Bildung\60_Self_Online_Study\60_Programmieren\Projekte\CreditKonto_analysing' # 目录不存在则自动创建 os.makedirs(output_dir, exist_ok=True) output_path = os.path.join(output_dir, 'neue_datei.csv')
3. 统一读写编码避免冲突
读取时用了ISO-8859-1编码,写入时必须指定相同编码,否则会因编码不一致导致文件损坏或描述符错误:
df.to_csv(output_path, index=False, header=True, encoding='ISO-8859-1')
4. 检查文件资源占用
如果neue_datei.csv已被Excel等其他程序打开,会触发Bad File Descriptor错误,需先关闭相关程序再运行代码。
修改后的完整代码
import pandas as pd import os def read_csv_auto_header(file_path): # 转换为绝对路径并检查文件是否存在 abs_file_path = os.path.abspath(file_path) if not os.path.exists(abs_file_path): raise FileNotFoundError(f"输入文件不存在:{abs_file_path}") df = pd.read_csv(abs_file_path, encoding='ISO-8859-1', sep=';') df = df.replace('\s+', ' ', regex=True) # 确保输出目录存在 output_dir = r'D:\Markus\00_Documents\20_Bildung\60_Self_Online_Study\60_Programmieren\Projekte\CreditKonto_analysing' os.makedirs(output_dir, exist_ok=True) output_path = os.path.join(output_dir, 'neue_datei.csv') # 统一编码写入 df.to_csv(output_path, index=False, header=True, encoding='ISO-8859-1') # 使用绝对路径作为输入 file_path = os.path.abspath('Buchung.csv') read_csv_auto_header(file_path)
内容的提问来源于stack exchange,提问作者Markus Wiesinger
相关产品推荐
相关产品推荐

