Skip to content

Latest commit

 

History

History
67 lines (42 loc) · 1.27 KB

python-basic-file-manipulation.md

File metadata and controls

67 lines (42 loc) · 1.27 KB

Python Basic File Manipulation

Date: June 1, 2016

Introduction

Python is able to support file read and manipulation. The essential functions for file manipulation will be discussed.

File Open

file_handler = open ('this_is_your_file.file_format')

File Close

file_handler = open ('this_is_your_file.file_format')

# file manipulation logic must be here

file_handler.close()

Note: Don't forget to close.

File Read

file_handler = open ('this_is_your_file.file_format')

# will get all the content from the file
file_content = file_hanlder.read()

# will get content of file line by line
file_content = file_hanlder.readline()

file_handler.close()

Note: The readline function will keep track which line the program is currently reading.

File Write

file_handler = open ('this_is_your_file.file_format', 'w')
file_hanlder.write(some_data)
file_handler.close()

Truncate File Content

file_handler = open ('this_is_your_file.file_format', 'w')
file_hanlder.truncate()
file_handler.close()

Note: As soon as a file is opened in write mode, the file is already truncated.

References

Author

Almer Mendoza