如何在python3中找到文件的长度?

pyt*_*der 0 python text-files content-length

我的第一个.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)
Run Code Online (Sandbox Code Playgroud)

我的第二个.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')
Run Code Online (Sandbox Code Playgroud)

我无法找到input_file.

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

预期输出:

ef

然后,如果第 num = 2 行,我希望输出为“ef”。

小智 6

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

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