# Python file Handling :::info Table of Contents [TOC] ::: Several functions for creating, reading, updating, and deleting files #### file handling modes ``` "r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists ``` ``` "t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images) ``` #### read file `demo.txt` ``` Hello, Im a demo txt file. this is the second line of this file. Good bye~ ``` *open file and read* ```python= # _file = open("<file's location>", "<mode>") # _print(_file.read(<the num of characters you want to get>)) _file = open("demo.txt", "r") print(_file.read()) ``` *readline* ```python= # print(_file.readline()) _file = open("demo.txt", "r") print(_file.readline()) ``` *file close* ```python= # _file.close() _file = open("demo.txt", "r") print(_file.readline()) _file.close() ``` #### create/ writing file *write/ overwrite file* ```python= # f.write("<contents>", "<mode>") f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() # f = open("demofile2.txt", "r") # print(f.read()) ``` ```python= # f = open("<>") f = open("myfile.txt", "x") ```