Topic 4: Files
Learning Outcomes:
(a) Identify the use of input/output files using CSV and text files
CP125
Topic 4: Files
Table of content
CP125
Learning about text files in Python is important because:
2. Type of File in Python
There are 2 type of files in python
What is text File ?
(like bold or italic) or binary data
Figure 1
.txt
Common
Text File Format
.json
.csv
.yaml
.xml
.yaml
.csv
.txt
demofile.txt
Reference What is csv file
daily_expenses
What is .txt and .csv File
Structure of .csv File
open in excel
open in notepad
Record
Field
Header
3. File Operation for .txt and .csv file
Basic file operations
2. Read File
3. Write to File
4. Close File
Python provides built-in functions and external modules(csv) to support these operations
.txt File
3. Working with .txt file
.txt Python File Operation Functions & Methods
open file
f= open(path_to_file,mode)
read file
f.read() # read entire content of the file as a STRING
f.readline() # read a single line from a file as a STRING
f.readlines()# read all lines in the file and return them as a LIST of STRING
write to file
f.write() # write a single line to a file
f.writelines() # write a list of string to a file
close file
f.close() # close the file
f= open(path_to_file,mode)
‘path/to/txt/file/expenses.txt’
r - read
a - append
w - write
The mode you pick decides what action you can do with the file and behaviour of the file.
r+ - read/write
a+ - append/read
w+ - write/read
Opening Mode Description,Action and Behavior
Opening File Syntax in Different File Location
File location | Opening File Syntax | |
Same folder |
f=open(‘demo.txt’,w+) | |
Local File (e.g. inside Documents) | f=open(‘c:/User/user/Documents/project_folder/demo.csv’,w+) | |
Google Drive (Google Colab) |
f=open(‘/content/drive/MyDrive/project_folder/demo.txt’,w+) | |
Mode ‘w+’ , The file will be created if the file does not exist.
File Does Not Exist Error
Traceback (most recent call last):
File "c:/User/user/Documents/filenotexist.py", line 9, in <module>
f=open('demofiles.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'demofiles.txt'
Error Output
Opening File Syntax
*ERROR always happened cause by either wrong directory OR file does not exist
2. Reading File Syntax
f=open(path/to/csv/file/expenses.txt,w+)
f.read()
.txt file can be read using the built-in read function
output
Input file : demofile.txt
2(a) Reading Entire content of file
f = open("demofile.text", "r")
text = f.read()
print(f.read())
print(type(text))
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
<class 'str'>
output
Input file: demofile.txt
2(b) Reading a Single Line
It reads one line from the file each time it is called. Because it only called one, only one line is read.
output
demofile.txt
2(b) Reading a Single Line (contn’)
It reads one line from the file each time it is called, the program output first and second line as the method readline() is called twice
demofile.txt
output
2(c) Reading all Lines
It reads all line, and output a list of string,
each element represent a line in the file.
2(c)(1.0) Reading all Lines - from google colab
We may come across error if your input TEXT file contains unacceptable encoding style(refer to the error message). Make sure input file contains TEXT only, no funny characters.
File location in colab
2(c)(2.1) Reading all content - from google colab
read(), readline(), readlines()
NOTE: return values are string
2(c)(2.2) Reading a line of the content - from google colab
read(), readline(), readlines()
NOTE: Return values are string
2(c)(2.3) Reading all content - from google colab
read(),readline(), readlines()
Return value is a list.
2(c)(3.0) Reading all Lines - from google colab
We can use “with …. “ as well
The write() method writes a specified text to the file.
Where the specified text will be inserted depends on the open file mode and stream position.
"a": The text will be inserted at the current file stream position, default at the end of the file.
"w": The file will be emptied before the text will be inserted at the current file stream position, default 0.
3. Write File Syntax
3. Write File Syntax
f=open(path/to/csv/file/expenses.txt,w+)
f.write(‘content to write\n’)
or
f.write(‘content to write’+’\n’)
\n is added to the end of the string to ensure the next string start at a new line.
3(a) Write a Single String to File
output
3(a) Write a Single String to File (cont’)
output
3(b) Write list of String to File
output
4. Close File
file.close()
In Python, it's important to close files after you've finished working with them to release system resources