Python 从文件读取,附加到列表
我正在努力:Python 从文件读取,附加到列表,python,python-3.x,Python,Python 3.x,我正在努力: 从文件中读取 将每个字符串附加到列表(从文件中,分隔符“,”) 遍历列表并将某些元素附加到其他两个列表中 我得到的是索引越界,但我也不确定类型中包含的内容是否为字符串类型。您的解析器存在一些问题,我也不太确定您试图实现什么(在测试文件内容方面)。在任何情况下,您都可以使用以下代码转换将文件读入列表: types,end_server_ip,end_server_alias = [],[],[] with(open('in.txt', "r")) as f: types =
我得到的是索引越界,但我也不确定类型中包含的内容是否为字符串类型。您的解析器存在一些问题,我也不太确定您试图实现什么(在测试文件内容方面)。在任何情况下,您都可以使用以下代码转换将文件读入列表:
types,end_server_ip,end_server_alias = [],[],[]
with(open('in.txt', "r")) as f:
types = [line.rstrip().split(",") for line in f] # Put List syntax to do list compreehension
k = 0
while k < len(types):
print(types[k])
if types[k][0] is not None: # acess types as index for row, and index for column
if type(types[k][0]) == type('string'):
print('Its a String!!!')
print(1)
end_server_ip.append(types[k][0])
if types[k][1] is not None:
print(2)
if type(types[k][1]) == type('string'):
print('Its a String!!!')
end_server_alias.append(types[k][1])
k += 1
f.close()
类型,终端服务器ip,终端服务器别名=[],[],[]
将(open('in.txt',r')作为f:
types=[line.rstrip().split(“,”)表示f中的行]#Put List语法进行列表压缩
k=0
而k
,请注意,我更改了定义类型的方式,更改了访问类型元素的方式,并添加了一个问题,以查看元素是否是字符串
请注意,该列表具有相当于行和列的内容,因此需要对行和列进行索引才能访问元素。从我从代码中看到的情况来看,询问一个元素是否为None对我来说有些奇怪。使用指令创建类型将始终创建字符串。如果你需要数字,你需要自己转换。请参阅int
和float
谢谢,我发现我误解了它在python中的工作原理。
168.1.2.6,www.random1.com
133.1.3.4,www.random2.com
types,end_server_ip,end_server_alias = [],[],[]
with(open('in.txt', "r")) as f:
types = [line.rstrip().split(",") for line in f] # Put List syntax to do list compreehension
k = 0
while k < len(types):
print(types[k])
if types[k][0] is not None: # acess types as index for row, and index for column
if type(types[k][0]) == type('string'):
print('Its a String!!!')
print(1)
end_server_ip.append(types[k][0])
if types[k][1] is not None:
print(2)
if type(types[k][1]) == type('string'):
print('Its a String!!!')
end_server_alias.append(types[k][1])
k += 1
f.close()