[how] Read And Write Files In Python


 

Files are the external storage container for data. They are part of input-output mechanism in Python.

#open, write and close a file
# append (a)
f = open("emolog.txt", "a")
f.write("I am happy\n")
f.close()

#try manipulating a file
try:
  # read (r)
  f = open("emolog.txt", "r")
  textData = f.read()
  f.close()  

  print(textData)
  
  #using with, no need to put close statement
  with open('emolog.txt') as f:
    textLineCount = len(f.readlines())
  
  print("{} line(s)".format(textLineCount))
  
  if(textLineCount)>10:
    # write (w)
    f = open("emolog.txt", "w")
    f.write("=== emolog ===\n")
    f.close()

except:
  #if a file is created for the first time,
  #the program may fail to detect during
  #the first run
  print('error reading file. try again.')
  
  
  


The mode is an optional parameter. It specifies the way a file is opened i.e. read (r), write (w), or append (a).

It is also possible to file access statement which automatically close the connection to the file using "with ..." statement.

Warning : Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

Further reading:

https://docs.python.org/3/tutorial/inputoutput.html

https://www.w3schools.com/python/python_file_handling.asp

https://www.pythontutorial.net/python-basics/python-read-text-file/

https://www.geeksforgeeks.org/file-handling-python/


Post a Comment

0 Comments