Почему при чтении файла с помощью `read()` в цикле появляются пустые строки?Python

Программы на Python
Anonymous
Почему при чтении файла с помощью `read()` в цикле появляются пустые строки?

Сообщение Anonymous »

Я просто пытаюсь понять, почему в моем выводе появляются две дополнительные строки. Может кто-нибудь понять это для меня, пожалуйста?

Код: Выделить всё

#open, write, and read text file (e.g., "WordTextFile1.txt") using open(), write(), read()

file_name = (input())#store name of the file

with open(file_name,'r') as f:
word1 = str(f.read())
word2 = str(f.read())
word3 = str(f.read())

#solution accepts file input to insert sentence composed of file content into text file on a new line

f = open(file_name,"r")

lines = f.read().splitlines()
lines=' '.join(lines)
lines = lines.replace('\n', '')

f.close();#close the file

#solution outputs the text file contents including the new sentence

print(f"{word1}\n{word2}\n{word3}\n{lines}")
Изображение


Подробнее здесь: https://stackoverflow.com/questions/756 ... lank-lines

Вернуться в «Python»