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

前端 未结 23 2162
醉酒成梦
醉酒成梦 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:15
    with open("data.txt") as myfile:
        data="".join(line.rstrip() for line in myfile)
    

    join() will join a list of strings, and rstrip() with no arguments will trim whitespace, including newlines, from the end of strings.

    0 讨论(0)
  • 2020-11-22 06:15
    file = open("myfile.txt", "r")
    lines = file.readlines()
    str = ''                                     #string declaration
    
    for i in range(len(lines)):
        str += lines[i].rstrip('\n') + ' '
    
    print str
    
    0 讨论(0)
  • 2020-11-22 06:17

    It's hard to tell exactly what you're after, but something like this should get you started:

    with open ("data.txt", "r") as myfile:
        data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])
    
    0 讨论(0)
  • 2020-11-22 06:17

    you can compress this into one into two lines of code!!!

    content = open('filepath','r').read().replace('\n',' ')
    print(content)
    

    if your file reads:

    hello how are you?
    who are you?
    blank blank
    

    python output

    hello how are you? who are you? blank blank
    
    0 讨论(0)
  • 2020-11-22 06:17

    This is a one line, copy-pasteable solution that also closes the file object:

    _ = open('data.txt', 'r'); data = _.read(); _.close()
    
    0 讨论(0)
  • 2020-11-22 06:18
    f = open('data.txt','r')
    string = ""
    while 1:
        line = f.readline()
        if not line:break
        string += line
    
    f.close()
    
    
    print string
    
    0 讨论(0)
提交回复
热议问题