Python读取用户输入文本文件并逐词分行写入报错求助
Python文件读写问题排查与入门指引
问题背景
编写Python程序实现:读取用户指定的TXT文件,将文件内容按每个单词一行的格式写入新的TXT文件。固定文件名的版本可正常运行,但加入用户输入文件名的逻辑后,明明文件存在却提示文件不存在,需要排查问题并获得入门级解决指引。
无法运行的错误代码
outputString = " " userinput = input('Enter the name of the file you want to read:' + " ") myfile = open(userinput, 'r') # 错误:未定义userinput_Output变量 myOutputFile = open(userinput_Output, 'a') for line in myfile: words = line.split() for current in words: myOutputFile.write(current + "\n") myfile.close() myOutputFile.close()
可正常运行的固定文件名代码
outputString = " " myfile = open("readme.txt", 'r') myOutputFile = open("readme_Output.txt", 'a') for line in myfile: words = line.split() for current in words: myOutputFile.write(current + "\n") myfile.close() myOutputFile.close()
问题排查与解决
核心错误点
- 未定义输出文件名变量:错误代码中直接使用
userinput_Output,但这个变量从未赋值,会触发NameError,导致程序中断,容易被误以为是“文件不存在”的错误。 - 文件路径问题:若用户输入的文件名不在Python当前工作目录下,会触发
FileNotFoundError,需确认文件位置或输入完整路径。
修正后的代码
# 获取用户输入的文件名 userinput = input('请输入要读取的文件名:') # 基于输入文件名生成输出文件名(替换原后缀为_Output.txt) output_filename = userinput.replace('.txt', '_Output.txt') # 使用with语句自动管理文件,无需手动调用close() with open(userinput, 'r', encoding='utf-8') as myfile, open(output_filename, 'a', encoding='utf-8') as myOutputFile: for line in myfile: words = line.split() for current in words: myOutputFile.write(current + '\n')
入门级知识点指引
- 变量使用规则:所有变量必须先定义赋值,才能调用。比如输出文件名需要基于用户输入的字符串生成,不能直接使用未定义的名称。
- 文件路径认知:Python默认在当前工作目录查找文件,可通过
import os; print(os.getcwd())查看当前目录。若文件在其他位置,需输入完整路径(如Windows的C:\test\demo.txt,Linux/macOS的/home/user/demo.txt)。 - 文件操作最佳实践:使用
with语句打开文件,会在代码块结束后自动关闭文件,避免资源泄漏,比手动调用close()更安全。 - 异常处理:可加入异常捕获,提升程序健壮性,示例:
userinput = input('请输入要读取的文件名:') output_filename = userinput.replace('.txt', '_Output.txt') try: with open(userinput, 'r', encoding='utf-8') as myfile, open(output_filename, 'a', encoding='utf-8') as myOutputFile: for line in myfile: words = line.split() for current in words: myOutputFile.write(current + '\n') print("处理完成") except FileNotFoundError: print("错误:指定的文件不存在,请检查文件名或路径") except PermissionError: print("错误:没有文件读写权限") except Exception as e: print(f"发生未知错误:{e}")
内容的提问来源于stack exchange,提问作者KMIL
相关产品推荐
相关产品推荐

