1

My first.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)

My second.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')

I am unable to find the length of the input_file.

I do not know why. Can somebody please help me?

Expected Output:

ef

Then if line num =2 I want the output as "ef".

Rot-man
  • 18,045
  • 12
  • 118
  • 124
pythoncoder
  • 575
  • 3
  • 8
  • 17

3 Answers3

7

I stumbled upon the same question while doing a mini project.The below code worked for me:

with open("filename","r") as f:
    print(len(f.readlines()))  # This would give length of files.
Pavithra B
  • 141
  • 2
  • 6
2

I think this is what you're looking for. It iterates over the file line by line.

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

If you want the number of lines in the file, do the following.

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

Here's a basic tutorial on file operations for further reading.

Haran Rajkumar
  • 2,155
  • 16
  • 24
  • correct but i want that text line along with the line number – pythoncoder Mar 20 '19 at 06:03
  • how to find a particular word and print next line please help me – pythoncoder Mar 20 '19 at 06:08
  • You could use regular expressions to find a specific word in a line, https://docs.python.org/2/library/re.html, but this question is different from your initial one. Create a new question if you want answer to multiple questions. – Stef van der Zon Mar 20 '19 at 06:56
  • Is there any way to do this without iterating over each line or by loading the entire file into memory (as in this post)? – Hawklaz Oct 15 '20 at 06:27
0

The other solutions that I have seen load everything into memory which I do not have the luxury of doing when I got to this post. So you could create a manual counter for each line read.

with open(filename, 'r') as read_obj:
reader = reader(read_obj)
counter = 0
for row in reader:
    counter += 1
  • Hi, the indentation of your code isn't correct? Also please add where you're importing `reader` from. – D Malan Feb 24 '23 at 09:43
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 24 '23 at 09:43