无效文件错误Python?

2024-10-05 14:28:30 发布

您现在位置: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))

Tags: 文件topathnameyouinputoscount
1条回答
网友
1楼 · 发布于 2024-10-05 14:28:30

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

相关问题 更多 >