我有一个文本文件,我从中解析一列数据,结果是一个大列表(50 个元素):
CLB, HNRG, LPI, MTDR, MVO, NRGY, PSE, PVR, RRC, WES, ACMP, ATLS, ATW, BP, BWP, COG, DGAS, DNR, EPB, EPL, EXLP, NOV, OIS, PNRG, SEP, APL, ARP, CVX, DMLP, DRQ, DWSN, EC, ECA, FTI, GLOG, IMO, LINE, NFX, OILT, PNG, QRE, RGP, RRMS, SDRL, SNP, TLP, VNR, XOM, XTXI, AHGP
现在,在该列表中的每 10 个元素之后,我想要一个新行。所以我想接近它的方式是在每 10 个逗号将列表分成一个新行之后,这是我的方法:
import csv
import re
filename = input("Please enter file name to extract data from: ")
with open(filename) as f:
next(f)
data = f.readlines()
my_list2 = []
ticker_list = []
for line in data:
my_list = line.split()
my_list2.append(my_list[1])
for item in my_list2:
ticker_list = ', '.join(my_list2)
count = 0
for item in ticker_list:
if item == ",":
count += 1
if count == 10:
ticker_list = [i.split('\n')[0] for i in ticker_list]
print (ticker_list)
##with open("ticker_data.txt", "w") as file:
## file.write(', '.join(ticker_list))
但这似乎不起作用,是否有人为我提供解决方案,可以在 txt 文件中给我这个结果:
CLB, HNRG, LPI, MTDR, MVO, NRGY, PSE, PVR, RRC, WES,
ACMP, ATLS, ATW, BP, BWP, COG, DGAS, DNR, EPB, EPL,
EXLP, NOV, OIS, PNRG, SEP, APL, ARP, CVX, DMLP, DRQ,
DWSN, EC, ECA, FTI, GLOG, IMO, LINE, NFX, OILT, PNG,
QRE, RGP, RRMS, SDRL, SNP, TLP, VNR, XOM, XTXI, AHGP
谢谢,顺便说一句,我正在使用Python 3..