python - 如何在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相当陌生
解决方案
这里有两个问题:
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}')
推荐阅读
- r - How to Classify data frame Based on a Columns in R?
- mongodb - 如何根据数组中的键对 mongo doc 进行分组?
- sql - 消除多个条件并减少到一个(没有 OR 语句)
- azure - Azure, do we need Web Application Firewall (WAF)?
- svg - SVG Blink Issue On Scroll Up/Scroll Down
- java - Use string replace inside java 8 foreach
- c++ - The scalar type additionnal in C++
- java - 如何在某些缩放级别禁用 zoomIn/zoomOut 按钮,例如:分别为 zoomlevel 18 和 zoomlevel 0
- reporting-services - 如果文本框被隐藏,则隐藏一行
- android - 使用开关按钮启用和禁用 Firebase 通知