xxxxxxxxxx
# How to read, and print to the screen a file in python!
f = open('fileName', 'r')
print(f.read())
f.close()
# Where "fileName" is obviously the name of your file that you want to read.
xxxxxxxxxx
f = open("demofile.txt", "r")
print(f.read())
f.close()
#OR
with open("demofile.txt","r") as file:
print(file.read())
xxxxxxxxxx
#Read files with loop
#Replace (File path) with your text file's path
file = open("(File path)", "r")
text = ""
for line in file:
text = "%s\n%s"%(text, line)
print(text)
xxxxxxxxxx
fileName = "file_name.txt" #Here you need to write the file name as a string
openLike = "" #Here you need to write how do you want to open the file:
#"w": Write, "r": Read
openedFile = open("file_name.txt", openLike) #Here you open the file
fileText = openedFile.read() #This read all the file
openedFile.close() #Close the file
print(fileText) # Prints the file text
xxxxxxxxxx
txt = open('FILENAME.txt')
txtread = txt.read()
print(txtread)
print(txt.read())
xxxxxxxxxx
my_file = open("C:\\Users\\Python\\file.txt", "r")
#Give the path accurately and use \\
text = my_file.read()
print(text)
#Output: The text in file.txt will be printed
xxxxxxxxxx
lines = []
with open('the-zen-of-python.txt') as f:
lines = f.readlines()
count = 0
for line in lines:
count += 1
print(f'line {count}: {line}')
Code language: JavaScript (javascript)