Reputation: 319
I'm trying to write a script that allows a user to create a folder with any name they want, and then create a file with any name they want. Once they do they, the program asks them for 3 names and writes them into the file. I then want to allow the user to input a number from 1 to 3 and display the number of lines they want. I'm getting an error right now when trying to read the file saying something along the lines of
TypeError: invalid file: <_io.TextIOWrapper name='C:blah blah ' mode='a' encoding='cp1252'>
The code is below:
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))
Upvotes: 3
Views: 10432
Reputation: 12245
You have newFile
defiled as an opened file. Then you open it within a while
loop, and it is a file, again.
And when you try then to open a file using the newFile
variable, Python tries to open a file with a name, contained in a newFile
variable. But it is not a file name - it is a file!
This makes Python sad...
Try this one:
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)
Upvotes: 6