【问题标题】:how to find the length of the file in python3?如何在python3中找到文件的长度?
【发布时间】:2019-03-20 05:43:09
【问题描述】:

我的第一个.py:

def create_file(file_name):
list=["ab","cd","ef"]
for i in list:
    with open(file_name, "a+") as input_file:
        print(" {}".format(i), file = input_file)

我的第二个.py:

from first import create_file
def read_file(file_name):
# Create file with content
create_file(file_name)

# Now read file content
input_file = open(file_name, 'r')
for text_line in input_file:     
   for line in range(len(input_file)):
      if "cd" in text_line :
         word = (input_file[line + 1])
         print(word)


 read_file('ss.txt')

我找不到input_file 的长度。

我不知道为什么。有人可以帮帮我吗?

预期输出:

ef

如果 line num =2 我希望输出为“ef”。

【问题讨论】:

  • 长度还是尺寸?
  • ss.txt 文件的长度
  • 示例:0 ab 1 cd 2 ef
  • 然后您正在寻找行数。请参阅下面我的答案中的编辑
  • 您给出的示例含糊不清。请详细说明。

标签: python text-files content-length


【解决方案1】:

我在做一个迷你项目时偶然发现了同样的问题。下面的代码对我有用:

with open("filename","r") as f:
    print(len(f.readlines()))  # This would give length of files.

【讨论】:

    【解决方案2】:

    我想这就是你要找的。它逐行遍历文件。

    input_file = open(file_name, 'r')     
    for line in input_file.readlines():
        print(line)
    

    如果您想要文件中的行数,请执行以下操作。

    lines_in_file = open(file_name, 'r').readlines()
    number_of_lines = len(lines_in_file)
    

    Here's文件操作基础教程,供进一步阅读。

    【讨论】:

    • 正确,但我想要该文本行以及行号
    • 如何找到一个特定的单词并打印下一行请帮助我
    • 您可以使用正则表达式在一行中查找特定单词docs.python.org/2/library/re.html,但这个问题与您最初的问题不同。如果您想回答多个问题,请创建一个新问题。
    • 有什么方法可以做到这一点,而无需遍历每一行或将整个文件加载到内存中(如本文所述)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多