2015-03-23 2 views
2

Я пытаюсь написать сценарий, который позволяет пользователю создать папку с любым именем, которое они хотят, а затем создать файл с любым именем, которое они хотят. Как только они это сделают, программа запрашивает у них 3 имени и записывает их в файл. Затем я хочу разрешить пользователю вводить число от 1 до 3 и отображать количество строк, которые они хотят. Я получаю ошибку прямо сейчас, пытаясь прочитать файл, говорящий что-то вроде строкНеверная ошибка файла Python?

TypeError: недействительный файл: < _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)) 

ответ

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) 
+0

Спасибо, сэр! Казалось, это трюк! – OysterMaker

+0

@BrandonGandy Добро пожаловать =) Будьте осторожны с переменными в динамически типизированных языках (например, Python, Ruby, JavaScript и т. Д.) - им все равно, назначите ли дескриптор файла строковой переменной и попробуйте вызвать 'open' с ним;) – shybovycha

+0

Вы посмотрите на мой код и посмотрите, почему мой вывод строк чтения работает неправильно? – OysterMaker

Смежные вопросы