Pandas DataFrame.to_csv raising FileNotFoundError:[Errno 2] No such file or directory

2ic8powd  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(102)

Hi:我尝试使用Pandas DataFrame.to_csv方法将一个文件夹保存到一个csv文件中:to_csv对15个文件工作正常,对一个文件抛出错误。我循环遍历Excel文件中的所有工作表,为每个选项卡创建单独的文件夹,并将csv文件放在相应的选项卡中。同一段代码在测试中工作,但在prod中失败。

for sheet_name in xls.sheet_names:
    df = pd.read_excel(xls, sheet_name=sheet_name, dtype = str, keep_default_na = False)
    csv_file_name = f"{os.path.splitext(excel_file)[0]} - {sheet_name}.csv"
    # Create a folder with the sheet's name if it doesn't exist
    sheet_folder_path = os.path.join(processed_directory, sheet_name)
    if not os.path.exists(sheet_folder_path):
        os.makedirs(sheet_folder_path)      
    csv_file_path = os.path.join(sheet_folder_path, csv_file_name)                        
    
    df.to_csv(csv_file_path, index=False,sep = '~')

字符串
20 Excel文件与8标签,它应该被转换为20 CSV文件与8个文件夹。请帮助。

jqjz2hbq

jqjz2hbq1#

使用pathlib确保您以运行系统的写入格式写入路径。

from pathlib import Path
sheet_folder_path = os.path.join(processed_directory, sheet_name)
mydir = Path(sheet_folder_path) 

if not os.path.exists(mydir):
      mydir.mkdir(parents=True, exist_ok=True)

csv_file_path = os.path.join(sheet_folder_path, csv_file_name)    
csv_file_path = Path(csv_file_path)          
df.to_csv(csv_file_path, index=False,sep = '~')

字符串

相关问题