我正在尝试编写一个脚本,允许用户创建一个具有任意名称的文件夹,然后创建一个具有任意名称的文件。一旦他们这样做了,程序会要求他们输入3个名字并将它们写入文件。然后我想允许用户输入一个从1到3的数字,并显示他们想要的行数。我现在有个错误,当我试图读取文件时
TypeError: invalid file: <_io.TextIOWrapper name='C:blah blah ' mode='a' encoding='cp1252'>
代码如下:
import os, sys
folder = input("What would you like your folder name to be?")
path = r'C:\Users\Administrator\Desktop\%s' %(folder)
if not os.path.exists(path): os.makedirs(path)
file = input("What name would you like for the file in this folder?")
file = file + ".txt"
completePath = os.path.join(path, file)
newFile = open(completePath, 'w')
newFile.close()
count = 0
while count < 3:
newFile = open(completePath, 'a')
write = input("Input the first and last name of someone: ")
newFile.write(write + '\n')
newFile.close()
count += 1
infile = open(newFile, 'r')
display = int(input("How many names from 1 to 10 would you like to display? "))
print (infile.readlines(5))
您已将
newFile
定义为打开的文件。然后在while
循环中打开它,它又是一个文件。当您尝试使用
newFile
变量打开一个文件时,Python会尝试打开一个名为的文件,该文件包含在newFile
变量中。但它不是一个文件名-它是一个文件!这让Python很伤心。。。
试试这个:
相关问题 更多 >
编程相关推荐