2

IDLE выдает ошибку такого плана:

Traceback (most recent call last):
File "C:/Python34/dodada8.py", line 26, in <module>
openFile.fileOpen(fileName)
File "C:/Python34/dodada8.py", line 11, in fileOpen
fileOpen = open("C:\file2_3.txt","w")
OSError: [Errno 22] Invalid argument: 'C:\x0cile2_3.txt'

Вот код:

fileName = str(input("Choose of 3 files: file2_1, file2_2, file2_3: "))

class fileConnector:

   def fileOpen(self, fileName):
     if fileName in ("file2_1","file2_2","file2_3"):

       if fileName == "file2_1":
           fileOpen1 = open("C:\file2_1.txt","w")
       elif fileName == "file2_2":
           fileOpen1 = open("C:\file2_2.txt","w")
       elif fileName == "file2_3":
           fileOpen1 = open("C:\file2_3.txt","w")
     else:
       print("File name is wrong")



class fileWriter:

   def fileWrite(self):
        write_str = str(input("Type any message: "))
        fileOpen1.write(write_str)
        fileOpen1.close()



openFile = fileConnector()
openFile.fileOpen(fileName)

writeFile = fileWriter()
writeFile.fileWrite()            
0

1 ответ 1

5

Использование \ вызывает экранирование символов с строках. Например: \n, \t.

Поэтому у вас \f стало \x0c.

Варианты решения:

  • Используйте raw-строки: r"C:\file2_1.txt"
  • Экранируйте слеш: "C:\\file2_1.txt"
  • Используйте другой слеш: "C:/file2_1.txt". Он не вызывает экранирование, поэтому безопасный
  • Можно воспользоваться библиотекой pathlib для формирования пути через синтаксис:
    import pathlib
    path = pathlib.Path('C:/') / 'Windows' / 'System32' / 'Boot'
    print(path)  # C:\Windows\System32\Boot
    

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.