使用next
函数可以 进行所需的操作,但这并不是解决此问题的最简单,最易懂的方法。我不建议在这里尝试使用next
。
您在文件中的各行之间有一个for
循环,但是实际上您想一次读取两行,因为每个“项目”数据都取决于文件中的两行。我建议分三个部分解决这个问题:
- 首先,设计一种将数据表示为对象(例如元组或namedtuple)的方法。
- 编写一个
while
循环以一次读取文件的两行,从这两行中提取数据以创建对象,并将这些对象收集在列表中。
- 遍历对象列表,从每个对象中打印出所需的数据。
第2部分的解决方案如下所示:
results = []
with open('vpn.txt','r') as f:
line1,line2 = f.readline(),f.readline()
while line1 and line2:
_,_,id_number,ip_address = line1.split()
algorithm = line2.split()[-1]
obj = (id_number,ip_address,algorithm)
results.append(obj)
line1,f.readline()
,
with open("vpn.txt") as f:
for index,(line1,line2) in enumerate(zip(f,f),start=1):
peer_ip = line1.split()[-1]
cipher_suite = line2.split()[-1]
print(index,peer_ip,cipher_suite,sep=',')
看到问题How do I read two lines from a file at a time using python
这只会得到每行的最后一个单词,一次只有两行。您还想进行一些错误检查,例如
if "peer" not in line1.split():
raise ValueError(f'Line {index} doesn\'t contain the word "peer",but it should: {line1}')
或尝试parse peer_ip
as an IP address
import ipaddress
def is_valid_ip_address(text):
try:
ipaddress.ipaddress(text)
return True
except ValueError:
return False
with open("vpn.txt") as f:
for index,start=1):
peer_ip = line1.split()[-1]
cipher_suite = line2.split()[-1]
if not is_valid_ip_address(peer_ip):
raise ValueError(
f'Line couldn\'t parse "{peer_ip}" as an IP address on line {index}'
)
print(index,sep=",")
,
您不能在str对象旁边使用
。
这是确切文件结构的解决方案
with open('vpn.txt','r') as fo
desired_line = ''
for line in fo:
list = line.split(" ")
if "peer" in list:
desired_line += list[3] + "," + list[6].strip()
else:
desired_line += "," + line.split(' ')[6]
print(desired_line)
desired_line = ''
,
您可以使用熊猫轻松地做到这一点。根据我所看到的,您的要求是获取第4,6,7列。我考虑过每一列都用tab('\ t')分隔。您甚至可以使用空间。
我使用了虚拟列名。您可以使用适当的一个。
import pandas as pd
df = pd.read_csv('vpn.txt',sep = '\t',header = None)
df.columns = ["A","B","C","D","E","F","G"]
OutputData = df[["D","G"]]
OutputData.to_csv('vpn2.txt',sep= '\t')
本文链接:https://www.f2er.com/3122054.html