Skip to content Skip to sidebar Skip to footer

How Do I Print The Content Of A .txt File In Python?

I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teachi

Solution 1:

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()

Solution 2:

withopen("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

Solution 3:

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

Solution 4:

print ''.join(file('example.txt'))

Solution 5:

How to read and print the content of a txt file

Assume you got a file called file.txt that you want to read in a program and the content is this:

this is the content of the file
withopen you can read it andthenwith a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line betweeneach (notempty) line

You can read this content: write the following script in notepad:

withopen("file.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

save it as readfile.py for example, in the same folder of the txt file.

Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:

C:\examples> python readfile.py

You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).

output

this is the content of the file
withopen you can read it andthenwith a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line betweeneach (notempty) line

Post a Comment for "How Do I Print The Content Of A .txt File In Python?"