我正在尝试将代码输出保存到csv文件中的两个不同列中。
Possessions
当前输出是IP的一列。我想要 主机名放在一栏中,然后相应的IP在下一栏中。
csv输出:
Possessions(
id int primary key,
pid_passer int not null references Players,
pid_passee int not null references Players,
time int not null, //the time the possession started for a player
held int not null //for how much time he had the ball
)
答案 0 :(得分:0)
使用tuple
列表存储您的输出。并使用csv
模块
例如:
import csv
import socket
from sys import argv
script, file1 = argv
lst = []
with open(file1) as f:
for line in f:
x = socket.gethostbyname(line.strip())
list.append((x, line))
with open('returned_hosts.csv', 'w', newline='') as r:
writer = csv.writer(r, delimiter="|")
writer.writerows(lst)
答案 1 :(得分:0)
保存为.csv格式时,最好使用csv module,它是专门为该目的而构建的。
答案 2 :(得分:0)
使用以下优化方法而不保存外部列表:
import socket
from sys import argv
file1 = argv[1]
with open(file1) as f_in, open('returned_hosts.csv', 'w') as f_out:
for line in f_in:
h_name = line.strip()
ip = socket.gethostbyname(h_name)
f_out.write(f'{ip}|{h_name}\n')
答案 3 :(得分:0)
您可以像使用csv
模块一样
$ cat write.py
import socket
import csv
with open('names.txt') as f, open('hosts.txt', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(('ip', 'name'))
for line in f:
line = line.strip()
if line:
ip = socket.gethostbyname(line)
writer.writerow((ip, line))
names.txt
的内容,
$ cat names.txt
google.com
twitter.com
然后以
的身份运行$ python write.py
输出:
$ cat data.txt
ip|name
172.217.160.142|google.com
104.244.42.193|twitter.com