You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Google Colab创建CSV文件时出现FileNotFound错误

Pandas DataFrame分割与Colab文件写入问题解答

问题描述

在Google Colab中尝试将Pandas DataFrame分割为多个较小的CSV文件时,出现FileNotFound错误,原本以为调用writerow会自动创建不存在的新CSV文件;同时不清楚如何在Colab中正常写入文件,也想确认代码中iloc的使用是否正确。

附代码

csv_counter = 1
for ind in bottle.index:
  try:
    if bottle['u'][ind] == 1 and bottle['u'][ind+1]==bottle['u'][ind]:
      f = "/content/drive/MyDrive/proj/datasets/036/{}.csv".format(csv_counter)
      csv_new = open(f, "w")    
      writer = csv.writer(csv_new)
      writer.writerow(bottle.iloc[ind])

    elif bottle['u'][ind] == 1:
      writer.writerow(bottle.iloc[ind])
      csv_counter += 1

  except:
    f = "/content/drive/MyDrive/proj/datasets/036/{}.csv".format(csv_counter)
    csv_new = open(f, "w")    
    writer = csv.writer(csv_new)
    writer.writerow(bottle.iloc[ind])

核心问题解答

1. FileNotFound错误的可能原因

  • 上级目录不存在:open()函数仅会自动创建文件,不会生成路径中的上级目录。如果/content/drive/MyDrive/proj/datasets/036/这个目录本身未创建,就会触发错误。
  • Drive未挂载:未在Colab中挂载Google Drive时,/content/drive/MyDrive/路径根本不存在,自然无法找到文件位置。

2. Google Colab中写入文件的正确方式

  • 先挂载Google Drive:执行以下代码完成挂载,按提示完成授权登录:
    from google.colab import drive
    drive.mount('/content/drive')
    
  • 提前创建目录:用os.makedirs()生成所需目录,避免路径不存在问题:
    import os
    save_dir = "/content/drive/MyDrive/proj/datasets/036/"
    os.makedirs(save_dir, exist_ok=True)  # exist_ok=True避免目录已存在时报错
    
  • 规范文件操作:用with语句自动管理文件资源,防止资源泄漏,同时避免重复打开覆盖内容:
    with open(f, "w") as csv_new:
        writer = csv.writer(csv_new)
        writer.writerow(bottle.iloc[ind])
    

3. iloc使用的正确性验证

代码中bottle.iloc[ind]的用法是正确的:iloc用于按位置索引获取行数据,当ind是DataFrame的整数位置索引时,能正常获取对应行。但如果你的DataFrame使用非整数索引(如字符串索引),ind不是位置序号,这时iloc[ind]会报错,需改用loc[ind]。从代码逻辑看,假设bottle.index是默认整数序列,当前用法没问题。

另外代码存在其他潜在问题:

  • 每次写入一行都重新打开文件,"w"模式会覆盖之前的内容,应该保持文件打开直到写完对应行再关闭。
  • elif分支直接使用writer,若第一次循环就进入该分支,writer未定义会触发错误,这也是依赖except块的原因,但并非正确处理方式。

优化后的代码示例(修正逻辑与文件操作):

import csv
import os
from google.colab import drive

# 挂载Drive
drive.mount('/content/drive')

# 创建保存目录
save_dir = "/content/drive/MyDrive/proj/datasets/036/"
os.makedirs(save_dir, exist_ok=True)

csv_counter = 1
current_writer = None
current_file = None

for ind in bottle.index:
    # 获取当前行的u值
    u_current = bottle['u'].iloc[ind]
    
    if u_current == 1:
        # 检查是否需要新建文件
        if current_writer is None:
            file_path = os.path.join(save_dir, f"{csv_counter}.csv")
            current_file = open(file_path, "w", newline='')
            current_writer = csv.writer(current_file)
        
        # 写入当前行
        current_writer.writerow(bottle.iloc[ind])
        
        # 检查下一行是否还是u=1,否则关闭文件并更新计数器
        if ind < len(bottle)-1 and bottle['u'].iloc[ind+1] != 1:
            current_file.close()
            current_writer = None
            csv_counter += 1
    else:
        # 当前行u不等于1时,关闭已打开的文件
        if current_file is not None:
            current_file.close()
            current_writer = None

# 循环结束后关闭最后一个未关闭的文件
if current_file is not None:
    current_file.close()

内容的提问来源于stack exchange,提问作者exammuger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:20:32