[Solved] Reading a text file in python [closed]


Here is an example of reading and writing a text file below. I believe that you are looking for the “open” method.

with open('New_Sample.txt', 'w') as f_object:
      f_object.write('Python sample!\n')
      f_object.write('Another line!\n')

You simple open the file that you want and enter that file name as the first argument, and then you use ‘w’ as the second argument to write the file. If you Python file and text files are in different directories, you may have to also use the relative or absolute path to open the file. Since my Python file and text file are both in “Downloads” I do not have to do that in this scenario.

Here is the code below to read in a text file:

with open('New_Sample.txt') as f_object:
      for line in f_object:
           print(line.rstrip())

And here is the output:

Python sample!
Another line!

You simply use the open method again and you can print the files in the .txt file line for line in a loop. I use rstrip() in this case though because you will have some white space when you attempt to print the lines.

solved Reading a text file in python [closed]