python - 打开文件进行读取并返回字节数和换行符的函数

标签 python

我目前正在通过免费的在线 Python 学校学习。下面的模板已经给了我,我要完成这个函数,以便它返回文件的大小(字节数)和换行符的数量(“\n”)。我完全被困住了。任何帮助,将不胜感激。

def readFile(filename):
    f = open(filename)
    size = 0
    lines = 0
    buf = f.read()     
    while buf!="":



        buf = f.read() 

    f.close()                 

    return (size, lines)

最佳答案

因此,buf 变量包含一 block 数据。

由于您仍在学习,我将使用一个非常基本的方法:

nl_count = 0  # Number of new line characters
tot_count = 0  # Total number of characters
for character in buf:
    if character == '\n':
         nl_count += 1
    tot_count += 1

现在您必须调整它以适合您的代码,但这应该为您提供一些开始的东西。

关于python - 打开文件进行读取并返回字节数和换行符的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24162665/

相关文章:

python - Pandas 如何截断分钟,秒 pandas.tslib.Timestamp

python - 在 Python 中反射(reflect)/检查封闭变量

python - PyTorch 的 `no_grad` 函数在 TensorFlow/Keras 中的等价物是什么?

python - Pandas 数据帧 : Calculate Sum based on boolean values in another column

python - 使用 python 将字典值写入 csv 中的单独列

python - 按行拆分数据框并在 python 中生成数据框列表

python - Spacy:保存解析后的模型

python - 使 Matplotlib 按钮回调立即生效,而不是在将鼠标移开按钮后生效

python - Google colab 文件下载失败获取错误

Python BeautifulSoup 提取字体标签的内容