下面是一个 Python 程序的示例,它可以打开用户在命令行中指定的文件,打印输入的文件数,对每个文件中的数字求和,并打印文件名和文件名。数字总和:
import sys
# Get the file names from the command line arguments
file_names = sys.argv[1:]
# Print the number of files entered
print(f"You entered {len(file_names)} files.")
# Loop through the file names
for file_name in file_names:
# Open the file
with open(file_name, "r") as f:
# Read the contents of the file
contents = f.read()
# Split the contents of the file into a list of numbers
numbers = contents.split()
# Sum the numbers in the list
sum = 0
for number in numbers:
sum += int(number)
# Print the name of the file and the sum of the numbers
print(f"{file_name} sum: {sum}")
该程序使用 sys 模块从命令行参数中获取文件名,然后循环遍历文件名以打开每个文件,读取其内容,将内容拆分为数字列表,对列表中的数字求和,并打印文件名和数字的总和。
要使用这个程序,您可以从命令行运行它并将文件名作为参数传递,如下所示:
python program.py file1.txt file2.txt file3.txt