如何在python中拆分txt中的项目?
我在文本文件中有以下代码:如何在python中拆分txt中的项目?,python,python-3.x,list,text,Python,Python 3.x,List,Text,我在文本文件中有以下代码: 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
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'
回溯(最近一次呼叫最后一次):
文件“test.py”,第3行,在
行。拆分(“:”)
AttributeError:“list”对象没有属性“split”
我怎样才能解决这个问题?我对python相当陌生,这里有两个问题:
返回文件中所有行的列表readlines()
返回一个列表,它不是就地操作split
with open('config.txt', 'r') as configfile:
lines = configfile.readlines()
for item in lines:
item.split(': ')
HOST = item[1]
PORT = item[3]
print(f'Your host is {HOST} and port is {PORT}')
如果需要索引不同的列表字符串,也可以使用range函数
with open('config.txt', 'r') as configfile:
lines = configfile.readlines()
for i in range(0,len(lines):
split_string = lines[i].split(': ')
HOST = split_string [1]
PORT = split_string [3]
print(f'Your host is {HOST} and port is {PORT}')
简单修复:
with open('config.txt', 'r') as configfile:
lines = configfile.readline()
lines = lines.split(': ')
HOST = lines[1].split()[0]
PORT = lines[2]
print("Your host is {HOST} and port is {PORT}".format(HOST = HOST, PORT = PORT))
readline()
而不是readline()
lines=lines.split(“:”)
with open('config.txt', 'r') as configfile:
lines = configfile.readline()
lines = lines.split(': ')
HOST = lines[1].split()[0]
PORT = lines[2]
print("Your host is {HOST} and port is {PORT}".format(HOST = HOST, PORT = PORT))
readline()
以字符串形式返回文件中的一行readlines()
以
字符串列表/数组行
变量
使用返回的结果with open('config.txt', 'r') as configfile:
lines = configfile.readline()
lines = lines.split(': ')
HOST = lines[1].split()[0]
PORT = lines[2]
print("Your host is {HOST} and port is {PORT}".format(HOST = HOST, PORT = PORT))
Config.txt:
Host: 0.0.0.0 Port: 80
输出:
Your host is 0.0.0.0 and port is 80
有两个问题,1)
lines.split(“:”)
,使用lines=lines.split(“:”)
返回一个新对象。2) readlines()
返回所有行的列表。您可以对configfile.readlines()中的行使用:
或对configfile:中的行使用,以逐个获取值。您希望的输出是什么?如果拆分该示例,(解决了您的另一个问题),您将得到“您的主机是0.0.0.0端口,端口是80”
下次首次使用print()
和print(type(…)
查看变量中的内容