Read File in Python
Create a file "hello.txt" with text as show below.
If the file is in a different directory - specify 
the full path
---------------------------------------------------

Hello World
 - read from Python

---------------------------------------------------

----------------------------------------------------------------------------
Create a file "readFile.py" with content as shown below.
----------------------------- readFile.py ----------------------------------
#!/usr/bin/env python

filename = "hello.txt"

with open(filename) as f:
    content = f.readlines()

#print(content)

count = 0
# Strips the newline character
for line in content:
    count += 1
    print("{}: {}".format(count, line.strip()))
--------------------------------------------------------

Read File

Read/write File in Python
1. Open file (fileout.txt) in write (w) mode
2. Write header and detail lines to the file
3. Close the file

---------------------------------------------------------------------------
Create a file "readWrite.py" with content as shown below.
----------------------------- readWrite.py --------------------------------
#!/usr/bin/env python

fileop = open("fileout.txt",'w')

hdr = "File Header\n"
dtl = ["1: first line\n", "2: second line\n", "3: third line\n"]

fileop.write(hdr)

fileop.writelines(dtl)

fileop.close()

print("Created file ",fileop)

filec = open('fileout.txt', 'r')

print("\nReading file ",filec)
print("\n")
print(filec.read())
filec.close()


Read write a file

  Compute Euler Constant (EXP)
  Python Reference


Last Revised On: April 17th, 2021

  759