Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印文件内容并计算文件中的行数-Python_Python - Fatal编程技术网

打印文件内容并计算文件中的行数-Python

打印文件内容并计算文件中的行数-Python,python,Python,介绍使用python编程课程 本周我们的任务是创建一个名为“randomnum.txt”的文本文件,并使用python脚本将其打印出来。我能够成功地创建文件,但我遇到了任务的第二部分,即打印文件内容并计算.txt中的数字(行) 我已经能够打印内容或计算行数,但从未两者兼而有之。我对Python很在行,需要一些帮助 with open ('randomnum.txt','r') as random_numbers: num_nums = 0 contents = random_

介绍使用python编程课程

本周我们的任务是创建一个名为“randomnum.txt”的文本文件,并使用python脚本将其打印出来。我能够成功地创建文件,但我遇到了任务的第二部分,即打印文件内容并计算.txt中的数字(行)

我已经能够打印内容或计算行数,但从未两者兼而有之。我对Python很在行,需要一些帮助

with open ('randomnum.txt','r') as random_numbers:
    num_nums = 0  
    contents = random_numbers.read()
    for lines in random_numbers:
        num_nums += 1
    print('List of random numbers in randomnum.txt')
    print(contents)
    print('Random number count: ', num_nums) 
这样,它给了我一个0的随机数计数


任何帮助都将不胜感激

调用
.read()
并使用
对。。。在…
中,两者都使用文件的内容。除非在两者之间调用
.seek(0)
,否则无法同时执行这两项操作。或者,您可以不调用
.read()
,而是捕获
for
循环中的行(可能切换到
.readlines()
),然后就不用担心了。

这是一个好问题,因为您观察到的行为是,您只能读取一次文件对象。一旦你调用了
随机数.read()
,你就不能重复这个动作了

我建议不要使用
.read()
,而是使用
.readlines()
。它逐个读取每一行,而不是一次读取整个文件。迭代每行时,将一行添加到计数器并打印当前行:

with open("file.txt", "r") as myfile:
    total = 0
    for line in myfile.readlines():
        print(line, end="")
        total += 1
    print("Total: " + str(total))

请注意我传递给print的第二个参数(
end=”“
)。这是因为默认情况下,
print
会添加一个换行符,但由于文件在换行符的末尾已经有了换行符,因此您将打印两个新行
end=”“
停止
print
打印尾随换行符的行为。

尝试此
readlines
然后
map
进行剥离,使用方法描述符进行剥离,然后使用
len
获取长度:

with open ('randomnum.txt','r') as random_numbers:
    l=random_numbers.readlines()
    print('List of random numbers in randomnum.txt')
    print(''.join(map(str.rstrip,l)))
    print('Random number count: ', len(l))
带有
randomnum.txt
的代码输出为:

1
2
3
4
5
6
输出:

List of random numbers in randomnum.txt
123456
Random number count:  6