how to read file python code example

Example 1: python read file line by line

with open("file.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)

Example 2: python read file

with open("file.txt", "r") as txt_file:
  return txt_file.readlines()

Example 3: python write to file

with open(filename,"w") as f:
  f.write('Hello World')

Example 4: python read file

txt = open('FILENAME.txt')
txtread = txt.read()
print(txtread)
print(txt.read())

Example 5: how to read files in python

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

Example 6: python open and read file with

with open('pagehead.section.htm','r') as f:
    output = f.read()