我正在尝试遍历命令行参数并打开给定的文件。我尝试通过使用读取行lines = file.readlines()
,然后使用 zip 来组合项目。但我不知道如何在不知道列表名称的情况下进行操作。这是我的代码:
import sys
import os
index = 1
while index < len(sys.argv):
if os.path.exists(sys.argv[index]) == True:
with open(sys.argv[index], 'r') as file:
lines = file.readlines()
#zip lines in files
index = index + 1
文件的内容是:
文件1:
12
27
59
文件2:
21
72
95
在这种方法中,您遍历每个参数,并附加到一个列表中,在每个文件的末尾,它将附加到一个新列表中,最终得到一个列表列表
import sys
import os
container = []
for document in sys.argv[1:]:
if os.path.exists(document):
aux = []
with open(document, 'r') as file:
for line in file:
aux.append(line.replace('\n',''))
container.append(aux)
print(*zip(*container))
然后你可以解压列表并压缩它,我手动替换行的跳转,做任何你想做的事情。;)
文件 1 包含
7
1
3
5
6
3
文件 2 包含
11
12
13
14
15
输入
python test.py test1.txt test2.txt
输出
('7', '11') ('1', '12') ('3', '13') ('5', '14') ('6', '15')
编辑
在“print(*zip(*container))”这一行中,我们正在解压缩容器,它是一个包含列表的列表,当我们压缩它时,正如您在压缩某些东西时所知道的那样,会创建一个 zip 对象,这是一个可迭代的,为了“解压缩”它并将其表示为一组元组,您可以使用 * (带星号的表达式),例如将其解包:
>>> a = zip([1,2,3,4,5], [5,4,3,2,1])
>>> print(a)
<zip object at 0x00000219ECE8C408>
>>> print(*a)
(1, 5) (2, 4) (3, 3) (4, 2) (5, 1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句