【问题标题】:My question is about opening files and printing a sum of contents我的问题是关于打开文件和打印内容总和
【发布时间】:2022-12-04 12:09:21
【问题描述】:

我是 python 和这个网站的新手,如果这是误用或愚蠢的问题,我也很抱歉。

在 python 中,我需要编写一个程序来打开用户在命令行上指定的文件,打印输入到屏幕的文件数,对每个文件中的所有数字求和,并打印文件名和屏幕上的数字总和。

输出如下:

您输入了 _files。 File1总和:

等等。

我正在尝试使用一个 for 循环,它将打开所有文件,读取所有内容并将其全部加起来,但我只是不断得到 0 的总和输出。谢谢大家!谢谢!

【问题讨论】:

  • 显示你的程序。我们需要阅读它以帮助您找出问题所在
  • 你能分享一些样本数据来处理吗

标签: python


【解决方案1】:

下面是一个 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

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多