Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

How can I split items in a txt in python?

I have the following code in a text file:

Host: 0.0.0.0 Port: 80
                        

This is my python code:

with open('config.txt', 'r') as configfile:
    lines = configfile.readlines()
    lines.split(': ')
    HOST = lines[1]
    PORT = lines[3]

print(f'Your host is {HOST} and port is {PORT}')

But I get this error:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    lines.split(': ')
AttributeError: 'list' object has no attribute 'split'

How can I fix this? I'm fairly new to python


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two issues here:

  • readlines() return a list of all the lines in the file
  • split returns a list, it's not an in-place operation
with open('config.txt', 'r') as configfile:
    lines = configfile.readlines() # lines will be a list of all the lines in the file
    line_split = lines[0].split(': ') # split returns a list, it's not an in-place operation
    print(line_split)
    HOST = line_split[1].split()[0]
    PORT = line_split[2]

print(f'Your host is {HOST} and port is {PORT}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...