首页 > 解决方案 > 如何在python中拆分txt中的项目?

问题描述

我在文本文件中有以下代码:

Host: 0.0.0.0 Port: 80
                        

这是我的python代码:

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}')

但我得到这个错误:

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

我怎样才能解决这个问题?我对python相当陌生

标签: pythonpython-3.xlisttext

解决方案


这里有两个问题:

  • readlines()返回文件中所有行的列表
  • split返回一个列表,它不是就地操作
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}')

推荐阅读