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

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

    with open(player_name, 'r') as myfile:
     data=myfile.readline()
     list=data.split(" ")
     word=list[0]
    

    This code will help you to read the first line and then using the list and split option you can convert the first line word separated by space to be stored in a list.

    Than you can easily access any word, or even store it in a string.

    You can also do the same thing with using a for loop.

提交回复
热议问题