python - 如何在 python 中将多个文件作为输入并存储在变量中
问题描述
我想从命令行获取多个文件作为输入
#python script.py file1.txt file2.txt file3.txt .... file_N.txt
以下程序只能将一个文件作为输入
python script.py file1.txt
但我想将多个文件作为输入。
import sys
with open(sys.argv[1], 'r') as file:
wordcount = file.read()
words= wordcount.split()
#print(words)
count = {}
for word in words:
if word in count:
count[word]=count[word] + 1
else:
count[word] = 1
print(count)
解决方案
它们存储在 sys.argv 中。它们存储在数组中,您可以通过索引访问它们。
a = str(sys.argv)
// a[0]: file1.txt
// ...
推荐阅读
- c# - 如何将当前日期插入到当前选定位置的richtextbox?
- javascript - 当两个 div 重叠时 - 第一个的颜色应该改变
- spring-websocket - Spring WebSocket ConvertAndSendToUser 不工作但 convertAndSend 工作
- for-loop - 这个 FOR 循环的时间和空间复杂度是多少?
- html - 如何将完成的网站发送给我的客户?
- python - Python:基于同一组的多个条目进入不同的列
- vba - 删除书签后的所有文本
- html - 如何淡出并用 CSS 动画替换单词?
- python - 如何检查“if”条件下的错误以做出决定?
- git - 有没有关于如何在 Jenkins 中使用 Job DSL 配置 GitLab 组的文档?