Lecture10 File Handling
Lecture10 File Handling
(File Handling)
Hyuntae Cho
Dept. of Digital Content
Tongmyong University
Python File Open
• File handling is an important part of any web application.
2
File Handling
• The key function for working with files in Python is the open()
function.
• The open() function takes two parameters; filename, and mode.
3
Syntax
• To open a file for reading it is enough to specify the name of the file:
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
4
Open a File
• Assume we have the following file, located in the same folder as
Python:
5
Read Only Parts of the File
• By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
• Example
– Return the 5 first characters of the file:
6
Read Lines
• You can return one line by using the readline() method:
• Read one line of the file:
• By calling readline() two times, you can read the two first lines:
• By looping through the lines of the file, you can read the whole file,
line by line:
7
Close Files
• It is a good practice to always close the file when you are done with
it.
• Example
– Close the file when you are finish with it:
8
Write to an Existing File
• To write to an existing file, you must add a parameter to the open()
function:
• Example
– Open the file "demofile2.txt" and append content to the file:
9
Write to an Existing File
• Example
– Open the file "demofile3.txt" and overwrite the content:
10
Create a New File
• To create a new file in Python, use the open() method, with one of
the following parameters:
• "x" - Create - will create a file, returns an error if the file exist
• "a" - Append - will create a file if the specified file does not exist
• "w" - Write - will create a file if the specified file does not exist
• Example
– Create a file called "myfile.txt":
Result: a new empty file is created!
11
Delete a New File
• To delete a file, you must import the OS module, and run its
os.remove() function:
• Example
– Remove the file "demofile.txt":
12
Check if File exist:
• To avoid getting an error, you might want to check if the file exists
before you try to delete it:
• Example
– Check if file exists, then delete it:
13
Delete Folder
• To delete an entire folder, use the os.rmdir() method:
• Example
• Remove the folder "myfolder":
14
Exercise
15
Conclusion
16