我试图编写一个脚本,允许用户创建一个包含他们想要的任何名称的文件夹,然后创建一个包含他们想要的任何名称的文件。一旦他们这样做,程序会询问他们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))
答案 0 :(得分:5)
您将newFile
玷污为已打开的文件。然后在while
循环内打开它,它又是一个文件。
当您尝试使用newFile
变量打开文件时,Python会尝试打开一个包含在newFile
变量中的名称的文件。但它不是文件名 - 它是一个文件!
这让Python很难过......
试试这个:
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) # completePath is a string
newFile = open(completePath, 'w') # here, newFile is a file handle
newFile.close()
count = 0
while count < 3:
newFile = open(completePath, 'a') # again, newFile is a file handle
write = input("Input the first and last name of someone: ")
newFile.write(write + '\n')
newFile.close()
count += 1
infile = open(completePath, 'r') # opening file with its path, not its handle
infile.readlines(2)