Python写入用户指定文件名的文件报错,求解决方案
问题描述
我需要创建并写入一个由用户输入命名的文件,文件名无法固定。我尝试通过输入变量创建文件,但之后需将更多用户输入追加到列表并写入该文件。
[省略部分内容]
以下是精简版代码(完整版含while循环与三个if语句),我将写入命令放在循环外,因为放入if语句块会完全失效。
编辑:根据反馈修改后,写入文件时仍抛出异常,附上更多代码,怀疑是写入命令位于if语句块外导致问题?
while True: try: print("Select:\n1. Create a file\n2. Open a file to add results to\n3. Read results from file") choice = int(input()) break except Exception as err: print(err) if choice == 1: print("Please enter the name of the file you would like to create (Must include .txt in name):") bmiFile = input() bmiEntry = open(bmiFile, 'w') print("Creating", bmiFile) bmiEntry.close() #Age entry while True: try: age = float(input("Please enter your age: ")) if age <= 0: raise TypeError ("Please enter a number greater than zero.") break except ValueError: print("Invalid input.") print("Please enter your age in numeric format.") except TypeError as err: print(err) except: print("Invalid input.") bmiIndex.append(age) try: bmiEntry = open(bmiFile, 'w') for i in bmiIndex: bmiEntry.write(i + '\n') except: print('Error writing to file.') bmiEntry.close()
问题分析与修复方案
你的代码存在几个核心问题:
- 变量作用域混乱:
bmiFile只在choice==1的分支里定义,如果用户选了其他选项,后续代码访问这个变量会直接报错;另外bmiIndex没有提前初始化,直接调用append会触发未定义异常。 - 类型错误:
age是浮点型,写入文件时直接用i + '\n'会报错——数字和字符串不能直接拼接,必须先转成字符串。 - 文件操作不规范:手动调用
close()容易因为异常导致文件未关闭,建议用with语句自动管理文件生命周期。 - 逻辑位置错误:写入文件的代码放在
if块外,不管用户是否选择创建文件都会执行,完全不符合业务逻辑。
修复后的代码示例:
# 提前初始化存储数据的列表 bmiIndex = [] while True: try: print("选择操作:\n1. 创建文件\n2. 打开文件添加内容\n3. 读取文件内容") choice = int(input()) if choice in [1,2,3]: break else: print("请输入1、2、3中的有效选项") except ValueError: print("输入无效,请输入数字选项") if choice == 1: print("请输入要创建的文件名(必须包含.txt后缀):") bmiFile = input().strip() # 用with语句自动处理文件关闭 with open(bmiFile, 'w') as bmiEntry: print(f"正在创建文件:{bmiFile}") # 年龄输入逻辑 while True: try: age = float(input("请输入你的年龄:")) if age <= 0: raise TypeError("请输入大于0的数字") break except ValueError: print("输入无效,请输入数字格式的年龄") except TypeError as err: print(err) except: print("输入无效,请重试") # 将年龄转成字符串存入列表 bmiIndex.append(str(age)) # 写入文件逻辑放到分支内,确保仅创建文件后执行 try: with open(bmiFile, 'w') as bmiEntry: for item in bmiIndex: bmiEntry.write(item + '\n') print("数据已成功写入文件") except Exception as e: print(f"写入文件出错:{e}") # 可在此补充choice==2和choice==3的逻辑实现
内容的提问来源于stack exchange,提问作者Stephanie Davi
相关产品推荐
相关产品推荐

