无效的文件错误Python? - python

我正在尝试编写一个脚本,该脚本允许用户使用他们想要的任何名称创建文件夹,然后使用他们想要的任何名称创建文件。完成后,程序会要求他们输入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))

python大神给出的解决方案

您已将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)