1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why does reading a file using `read()` in a loop produce blank lines?

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I'm just trying to figure out why I'm getting 2 extra lines in my output. Can someone figure this out for me please?

    #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}")


    [​IMG]

    Continue reading...

Compartilhe esta Página