To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.
Once you've got Notepad's settings right, try this trick: Open Windows Explorer and right-click a text file. On the context menu that appears, click Print. You no longer need to open Notepad first to tell it your preferences. Notepad remembers them for you.
Opening a file in python for reading is easy:
f = open('example.txt', 'r')
To get everything in the file, just use read()
file_contents = f.read()
And to print the contents, just do:
print (file_contents)
Don't forget to close the file when you're done.
f.close()
Just do this:
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
This will print the file in the terminal.
with open("filename.txt", "w+") as file:
for line in file:
print line
This with
statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for
loop
to input a file:
fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
to output this file you can do:
for element in fin:
print element
if the elements are a string you'd better add this before print:
element = element.strip()
strip()
remove notations like this: /n
print ''.join(file('example.txt'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With