计算任何数据文件中的两位数

2024-04-25 05:19:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算我输入的任何数据文件中的行数。该文件可以是任何.txt文件,每行有两位数字

我怎样才能使这项工作与任何数据文件,而不仅仅是一个特定的?如何将文件转换为字符串,然后将其存储在变量中?这是否意味着我只需要计算文件中的行数

#to open the file
file = input('Please enter the file name: ')
file = open(file, 'r')

#to display name of the assignment
    for assignment in file: 
    print('Results for', assignment)
    break

Tags: 文件theto字符串nametxtforinput
2条回答

要计算文件中的行数,请执行以下操作:

with open(file) as f:
    print(len(f.readlines()))

readlines将文件读入行列表,len将获得该列表的长度,最后print将其打印出来

但这是一个简单的解决方案,内存消耗O(n),其中n是文件中的行数。 最好这样做:

i = 0
with open(file) as f:
    for line in f:
        i += 1
count = 0
with open(file) as tests:
        for curline in tests: #for each line
            count+=1 #add int of line to total
print(count)

这是未经测试,但像这样的东西可能会工作?每行循环 将其转换为整数并追加总数

文件必须是文件的路径或文件名(如果与python文件位于同一目录中)。必须是字符串,如“testfile.txt”或“/files/myfile.txt”

如果是求和,则将计数更改为

count+=int(curline)

相关问题 更多 >