how can I read a text file in python ?I want python to show intended text file that I write it's name in python , and then I need a command to show me key words of that text file in a table.
-
1Possible duplicate of [In Python, how do I read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/in-python-how-do-i-read-a-file-line-by-line-into-a-list) – dave May 17 '18 at 18:29
-
Either the link above or numpy.genfromtxt can help you. Please do a quick search before posting!! – Joooeey May 17 '18 at 18:32
3 Answers
Read large text files in Python, line by line without loading it in to memory
check out this question title above, it may answer yours

- 11
- 4
The function you are looking for is open
if you run
with open("myVar.file") as f:
for i in f:
# Do work here
that should do what you want

- 1,664
- 14
- 27
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.

- 2,152
- 1
- 10
- 27