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

前端 未结 23 2447
醉酒成梦
醉酒成梦 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:01

    This works: Change your file to:

    LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
    

    Then:

    file = open("file.txt")
    line = file.read()
    words = line.split()
    

    This creates a list named words that equals:

    ['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']
    

    That got rid of the "\n". To answer the part about the brackets getting in your way, just do this:

    for word in words: # Assuming words is the list above
        print word # Prints each word in file on a different line
    

    Or:

    print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
    #The comma not in parentheses indicates a space
    

    This returns:

    LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN, GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
    

提交回复
热议问题