Skip to content

Instantly share code, notes, and snippets.

@writetomaha
Created March 14, 2018 09:26
Show Gist options
  • Save writetomaha/9038b459377762a0ee11cff366583849 to your computer and use it in GitHub Desktop.
Save writetomaha/9038b459377762a0ee11cff366583849 to your computer and use it in GitHub Desktop.
File Handling in Python
Storing, reading, working with files of an operating system
Types of File modes available
'r' : reading mode, this is the default mode which allows you to read the file not any modifications to the file.
'w': writing mode, this can be used for creating the new file as well.
'a': append mode, this is used to write the data to the end of the file, it does not clears any existing data.
#read(): read the contents from a text file
with open('myfile.txt', 'r') as f:
print(f.read())
#readline():read the contents line by line from a text file
with open('myfile.txt', 'r') as objFile:
contents = objFile.readline()
print(contents)
#readlines():returns the list containing all the lines from a text file
with open('myfile.txt', 'r') as objFile:
contents = objFile.readlines()
print(contents)
#read the data with certain limit
size_to_read = 10
with open('myfile.txt','r') as f:
print(f.read(size_to_read))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment