How to read a text file into a string variable and strip newlines?

前端 未结 23 2163
醉酒成梦
醉酒成梦 2020-11-22 05:47

I use the following code segment to read a file in python:

with open (\"data.txt\", \"r\") as myfile:
    data=myfile.readlines()

Input fil

相关标签:
23条回答
  • 2020-11-22 06:08

    Have you tried this?

    x = "yourfilename.txt"
    y = open(x, 'r').read()
    
    print(y)
    
    0 讨论(0)
  • 2020-11-22 06:10

    In Python 3.5 or later, using pathlib you can copy text file contents into a variable and close the file in one line:

    from pathlib import Path
    txt = Path('data.txt').read_text()
    

    and then you can use str.replace to remove the newlines:

    txt = txt.replace('\n', '')
    
    0 讨论(0)
  • 2020-11-22 06:11

    I have fiddled around with this for a while and have prefer to use use read in combination with rstrip. Without rstrip("\n"), Python adds a newline to the end of the string, which in most cases is not very useful.

    with open("myfile.txt") as f:
        file_content = f.read().rstrip("\n")
        print file_content
    
    0 讨论(0)
  • 2020-11-22 06:12

    You can read from a file in one line:

    str = open('very_Important.txt', 'r').read()
    

    Please note that this does not close the file explicitly.

    CPython will close the file when it exits as part of the garbage collection.

    But other python implementations won't. To write portable code, it is better to use with or close the file explicitly. Short is not always better. See https://stackoverflow.com/a/7396043/362951

    0 讨论(0)
  • 2020-11-22 06:12

    This can be done using the read() method :

    text_as_string = open('Your_Text_File.txt', 'r').read()
    

    Or as the default mode itself is 'r' (read) so simply use,

    text_as_string = open('Your_Text_File.txt').read()
    
    0 讨论(0)
  • 2020-11-22 06:12

    You can also strip each line and concatenate into a final string.

    myfile = open("data.txt","r")
    data = ""
    lines = myfile.readlines()
    for line in lines:
        data = data + line.strip();
    

    This would also work out just fine.

    0 讨论(0)
提交回复
热议问题