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

如何用Python写入文本/Excel文件至指定目录?及Jupyter代码异常排查

Python 文件写入问题解决与通用指南

一、你的代码运行失败的原因与修复

常见问题及解决办法:

  • 权限不足:Windows系统下C:\Users\ME\属于用户根目录,Jupyter Notebook默认可能没有写入权限。换个有权限的路径,比如桌面:
    def main():
        # 改为桌面路径
        outfile = open(r'C:\Users\ME\Desktop\philosophers.txt', 'w')
        outfile.write('John Locke\n')
        outfile.write('David Hume\n')
        outfile.write('Edmund Burke\n')
        outfile.close()
    
    if __name__ == '__main__':
        main()
    
  • 路径错误:确认你的系统用户名是否真的是ME——很多时候Windows用户名是真实姓名或自定义名称(比如C:\Users\张三\),可以通过文件资源管理器查看用户目录名称修正路径。
  • 验证工作目录:先运行以下代码确认Jupyter的当前工作路径,用相对路径写入更稳妥:
    import os
    print(os.getcwd())  # 打印当前工作目录
    # 相对路径写入,文件会出现在上述打印的目录下
    with open('philosophers.txt', 'w') as outfile:
        outfile.write('John Locke\nDavid Hume\nEdmund Burke\n')
    
  • 自动管理文件关闭:推荐用with语句,它会自动处理文件关闭,避免因程序异常导致的写入失败:
    def main():
        with open(r'C:\Users\ME\philosophers.txt', 'w') as outfile:
            outfile.write('John Locke\n')
            outfile.write('David Hume\n')
            outfile.write('Edmund Burke\n')
    
    if __name__ == '__main__':
        main()
    

二、Python 写入文本/Excel文件到默认/指定目录

1. 文本文件

  • 写入默认目录(当前工作目录):直接使用文件名,文件会生成在Jupyter的当前工作目录(可通过os.getcwd()查看):
    # 写入默认目录,指定utf-8编码避免中文乱码
    with open('test.txt', 'w', encoding='utf-8') as f:
        f.write('这是测试文本内容')
    
  • 写入指定目录:用os.path.join拼接路径,避免手动写路径时的转义字符问题:
    import os
    # 目标目录
    target_dir = r'C:\Users\ME\Documents'
    # 拼接完整文件路径
    file_path = os.path.join(target_dir, 'test.txt')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write('写入指定目录的文本内容')
    

2. Excel文件

先安装依赖库(处理.xlsx格式):

pip install pandas openpyxl
  • 写入默认目录:
    import pandas as pd
    # 构造测试数据
    data = {'姓名': ['张三', '李四'], '年龄': [25, 30], '城市': ['北京', '上海']}
    df = pd.DataFrame(data)
    # 写入默认目录,index=False关闭行索引
    df.to_excel('test.xlsx', index=False)
    
  • 写入指定目录:
    import pandas as pd
    import os
    target_dir = r'C:\Users\ME\Desktop'
    file_path = os.path.join(target_dir, 'test.xlsx')
    df.to_excel(file_path, index=False)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:30:51