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

调用自定义模块函数时无法读取data.txt文件问题求助

问题描述

调用自行编写的模块函数时,尝试读取data.txt文件,但函数无法访问该文件。文件本身存有数据,程序看似在执行填充操作,但生成的data.csv无任何输出。直接运行该文件而非作为模块时,程序运行完全正常。疑问:是否需要添加__init__.py?不清楚问题出在哪里。

调用代码

import csv_generator
# choose to print out in csv or json
def printData():
    answer = input('Please choose 1 for csv or 2 for jsson output file: ')
    if(answer == '1'):
        csv_generator.csv_write()
    elif(answer == '2'):
        json_writer.json_write()
    else:
        printData()

printData()

模块定义代码

import csv
def csv_write():
    # files to read from 
    data_read = open('data.txt', 'r')

    # process data and write to csv file
    with open('data.csv', 'w', newline='') as f:
        thewriter = csv.writer(f)

        thewriter.writerow(['Last', 'First', 'Email', 'Address', 'Phone'])
        for x in data_read:
            y = x.split(',')
            thewriter.writerow([y[0].strip(), y[1].strip(), y[2].strip(), y[3].strip(), y[4].strip()])
解决方案
  • 问题核心:文件路径不匹配
    直接运行模块文件时,程序的工作目录是该文件所在的目录;但将其作为模块导入时,工作目录是调用脚本所在的目录,而非模块文件的目录。所以open('data.txt', 'r')会去调用脚本的目录找文件,而非模块所在目录,导致读不到数据,最终生成空的csv。

  • 不需要添加__init__.py
    __init__.py用于标记Python包,单个模块文件无需该文件即可正常导入,这不是问题根源。

  • 修复方法
    修改模块中读取文件的路径,使用模块文件的绝对路径定位data.txt,确保无论模块在哪被导入,都能找到目标文件:

    import csv
    import os
    
    def csv_write():
        # 获取当前模块文件所在目录
        module_dir = os.path.dirname(os.path.abspath(__file__))
        # 拼接data.txt的绝对路径
        data_path = os.path.join(module_dir, 'data.txt')
        csv_path = os.path.join(module_dir, 'data.csv')
    
        # 用with语句同时管理读写文件,避免资源泄漏
        with open(data_path, 'r') as data_read, open(csv_path, 'w', newline='') as f:
            thewriter = csv.writer(f)
            thewriter.writerow(['Last', 'First', 'Email', 'Address', 'Phone'])
            for x in data_read:
                y = x.split(',')
                thewriter.writerow([y[0].strip(), y[1].strip(), y[2].strip(), y[3].strip(), y[4].strip()])
    
  • 额外修正
    调用代码里的jsson是拼写错误,需改成json,否则选择2时会触发报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:15:44