0

Есть код:

f = open('text.txt', 'w')
f.write("qwerty / asdfgh / zxcvbn")
f = f.replace('/', '\n')
f = open('text.txt', 'r')
f = f.read()
print(f)

Почему метод replace не работает? выдает ошибку:

'int' object has no attribute 'replace.

2
  • replace не будет работать с "указателем" на файл. Поменяйте до записи f.write("qwerty / asdfgh / zxcvbn".replace('/', '\n'))
    – splash58
    27 дек 2017 в 20:42
  • 1
    код в вопросе не может ошибку приведённую вызвать. Вы должны получить: '_io.TextIOWrapper' object has no attribute 'replace'
    – jfs
    29 дек 2017 в 15:05

1 ответ 1

3

Метод replace относится к строками, а не файловым объектам:

with open('text.txt', 'w') as f:
    text = "qwerty / asdfgh / zxcvbn"
    text = text.replace('/', '\n')
    f.write(text)  # 'qwerty \n asdfgh \n zxcvbn'

with open('text.txt', 'r') as f:
    text = f.read()  # 'qwerty \n asdfgh \n zxcvbn'
    print(repr(text))  
    print(text)
3
  • если метод replace не работает с указателем на файл. Тогда почему возвращается как раз таки указатель на файл из функции открытия документа? (Учу по книге Доусона, и из за этого такая ошибка и вылилась. def open file(file name. mode): the_file = open(file_name. mode. encoding='utf-8') return the_file def next_line(the_file): line = the_file.readline() line = line.replace("/", "\n") return line
    – Tafe SD
    29 дек 2017 в 15:21
  • А там тоже строка, т.к. .readline() возвращает строку
    – gil9red
    29 дек 2017 в 18:51
  • что ерунда ?def open file(file name. mode): the_file = open(file_name. mode. encoding='utf-8') return the_file def next_line(the_file): line = the_file.readline() line = line.replace("/", "\n") return line????????????????????????????????????????????????????????????????????????????????????????????????????? 10 янв 2018 в 1:01

Ваш ответ

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

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