0% found this document useful (0 votes)
4 views15 pages

Python File Processing Guide

The document provides an introduction to file processing in Python, highlighting its benefits such as automation, data processing, and support for various file types. It explains different file modes ('r', 'w', 'a', etc.) and methods for file operations, including reading, writing, and checking file properties. Additionally, it emphasizes the use of the 'with open' syntax for safe file handling.

Uploaded by

eric.chen951215
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

Python File Processing Guide

The document provides an introduction to file processing in Python, highlighting its benefits such as automation, data processing, and support for various file types. It explains different file modes ('r', 'w', 'a', etc.) and methods for file operations, including reading, writing, and checking file properties. Additionally, it emphasizes the use of the 'with open' syntax for safe file handling.

Uploaded by

eric.chen951215
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Computer Science (I)

File Processing

Yen-Ru, Lai
yrlai@[Link]

Department of Civil Engineering, National Chung Hsing University


Introduction to Computer Science (I) 8. File Processing

◼ Benefits of Python File Processing

1. Automated Tasks
Manually handling files (e.g., reading, writing, modifying) is time-consuming and prone to errors. Python can
automate these repetitive tasks.

2. Data Processing and Analysis


Python provides powerful tools (e.g., pandas and numpy) for handling large datasets, but the data must first be
read from files.

3. Support for Multiple File Types


Python supports various file operations, including text files, binary files (e.g., images or audio), and compressed
files (e.g., ZIP).

8-2
Introduction to Computer Science (I) 8. File Processing

◼ Python File Modes


File operations in Python depend on 【file modes】, which determine how the file can be accessed.
【File Models】
Model Illustration Overwrite or not
‘r’ Read mode (default). The file must exist. NO

‘w’ Write mode. If the file already exists, the content will be cleared; if it does not exist, Yes, overwrite the
a new file will be created. entire file
‘a’ Additional mode. Appends content at the end of the file. The file will be created if it
No, append to write
does not exist.
‘r+’ Yes, overwrite
Supports “read” and “write” at the same time, the file must already exist. character by
character
‘w+’ Supports "read" and "write" at the same time, the file must already exist.
Yes, overwrite the
entire file
‘a+’ Both "read" and "write" are supported, but are mainly used for appending content
No, append to write
and will not overwrite existing content. 8-3
Introduction to Computer Science (I) 8. File Processing

◼ Python File Modes


 File paths
1. Absolute Path
An absolute path starts from the root directory and provides the complete path to a file.
ex:
• Windows:
(1) C:/Users/YourName/Documents/[Link]
(2) r'C:\Users\user\Desktop\[Link]'
• Linux:
(1) /home/YourName/Documents/[Link]

2. Relative Path
A relative path is relative to the program's current working directory (CWD).
ex:
• File relative to current directory :data/[Link]
• Files located in the current directory : [Link] (Just enter the file name)
• Files in the previous directory :../[Link] 8-4
Introduction to Computer Science (I) 8. File Processing

◼ python built-in file processing

 1. Open file open()


file_variable = open(file_path and name, mode=“r”, encoding=“utf-8”)

• file_path and name: If only fill in the file name, the files in the same directory will be processed.
• Mode : Optional; defaults to 'r' (read-only).
• Encoding : Optional; utf-8 is recommended to avoid encoding issues.
• Open the file processor with the open() function. After the operation, remember to close it with close()!

# Read txt file(Absolute Path)


f1 = open("C:/Users/User/Desktop/[Link]", mode='r', encoding='utf-8')
# Read txt file(Relative Path)
f1 = open("[Link]", mode='r', encoding='utf-8’)
content = [Link]() # Read file contents
[Link]() # Close file manually
8-5
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


method Applicable modes Illustration
close() All acceptable Close file processor
Write a string to a file. If the file is opened in write or append mode, the contents
write(string) writable
will be written.
Read the contents of the file. If size is specified, the specified number of bytes are
read([size]) readable
read; otherwise, the entire contents are read.
Moves the file's read-write pointer to a position n bytes from the beginning of the
seek(n) All acceptable
file.
tell() All acceptable Returns to the position of the current pointer to the file (number of bytes).

readable() All acceptable Checks whether the file is readable, returning a Boolean value of True or False.

writable() All acceptable Checks whether the file was written, returning a Boolean value of True or False.
Read the characters of the specified length (size) of the row where the current text
pointer is located.
readline([size]) readable
If the parameter is omitted, the entire row (including the row break symbol\n) will
be read.
Read all rows and return a list. The elements of the list are row-by-row text in
readlines() readable
order. 8-6
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


1. write() : Writes a string to a file. Works in write ('w') or append ('a') mode.

# 'a’ file will be created and written if it does not exist


file = open('[Link] ', 'a', encoding='utf-8'))
[Link](‘Python file operation example\n')
[Link](' This is the second column. \n')
[Link]()

# 'w’ file will be overwritten if it exists


file = open('[Link]', 'w', encoding='utf-8'))
[Link]('Hello, World!')
[Link]()

8-7
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


2. read([size]): Reads content from the file.
If size is specified, reads the specified number of bytes. Otherwise, reads all content.
• read() can only be used in read mode or read-write mode(such as ‘r’ or ‘r+’);
it will throw an error if the file is opened in write-only mode(such as ‘w’ or ‘a’).
• Impact of the file pointer: Each time read(size) is used, reading will start from the
current file pointer, so you need to pay attention to the pointer position when calling
it repeatedly.
file = open('[Link]', 'r', encoding='utf-8'))
file = open('[Link]', 'r', encoding='utf-8')) content_1 = [Link]() # Read all bytes
content_1 = [Link](5) # Read the first 5 bytes # Read the next 5 bytes starting from the last byte so there is
content_2 = [Link]() # Read all bytes (start from the 6th byte) no content
print(content_1) content_2 = [Link](5)
print(content_2) print(content_1)
[Link]() print(content_2)
[Link]()
8-8
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


3. seek(n) : Moves the file read-write pointer to the nth byte from the start of the file.

file = open('[Link]', 'r', encoding='utf-8'))


[Link](6) # Move to 6th byte (counting from 0)
print([Link]()) # Read content starting from the 6th byte
[Link]()

4. tell() : Returns the position of the current pointer to the file (number of bytes).

file = open('[Link]', 'r', encoding='utf-8'))


print([Link]()) # Displays the current pointer position (usually 0)
[Link](5)
print([Link]()) # Show pointer position (should be 5)
[Link]()
8-9
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


5. readable() : Check whether the file is readable, returning a Boolean value of True or False.

# can be replicated (可複寫)but not readable 'w'


file = open('[Link]', 'w', encoding='utf-8'))
[Link]('Hello, World!')
print([Link]()) # File is opened in non-reading mode, output False
[Link]()

# Readable and writable 'a+'


file = open('[Link]', 'a+', encoding='utf-8'))
[Link]('Hello, World!')
print([Link]()) # File is opened in read mode, output True
[Link]()
8 - 10
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


6. writable() : Checks whether the file is writable, returning a Boolean value of True or False.
# Readable and writable (overwrite) 'w+'
file = open('[Link]', 'w+', encoding='utf-8') #The file already exists and the content will be cleared.
print([Link]()) # The file is opened in write mode, output True
[Link]()

# Readable and writable 'a+'


file = open('[Link]', 'a+', encoding='utf-8')
[Link]('Hello, World!')
print([Link]())
print([Link]()) # The file is opened in write mode, output True
[Link]()

8 - 11
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


7. readline([size]) : Read the characters of the specified length (size) of the column where the current text pointer
is located.
If the parameter is omitted, the entire column (including the column break symbol\n) will be read.

file = open('[Link]', 'w', encoding='utf-8')


[Link]('ABCDE\n')
[Link]('12345\n')
[Link]('67890\n')
[Link]()

file = open('[Link]', 'r', encoding='utf-8')


print([Link](0)) # The file pointer is at the beginning and contains no characters
print([Link](1)) #A : The file pointer moves one space backward from the beginning, and is located after the A character.
print([Link](3)) #BCD : The file pointer moves three spaces backward from the A character and is located after the D
character.
print([Link](6)) #E : When readline encounters a newline character (\n), it stops reading and returns the remaining
content, which is E.
[Link]()
8 - 12
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


8. readlines() : Read all rows in the file and return a list, with each row as an element of the list.

• readlines() starts reading from the current pointer position, and the‘a+’ mode is used in the program code, so that the file
pointer is located at the end of the file by default when the file is opened, which causes [Link]() to return an empty list [].

# [Link]() Return empty list [] file = open('[Link]', 'a+', encoding='utf-8')


file = open('[Link]', 'a+', encoding='utf-8') [Link](0) # Move the pointer to the beginning of the file
lines = [Link]() # Read all rows Correct print([Link]()) # Read all rows in the file
print(lines) [Link]()
[Link]()

• readlines() starts reading from the current pointer position, and the 'w+' mode is used in the
program code, so the file will be cleared when it is opened and readlines() cannot read anything.

file = open('[Link]', 'w+', encoding='utf-8')


lines = [Link]() # Read all columns
print(lines)
[Link]() 8 - 13
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


 readlines() 、readline([size]) reads different columns of data
【 Read the third column of data 】

# readline([size])method
file = open('[Link]', 'r', encoding='utf-8')
[Link]() # skip first column
[Link]() # skip second column
third_line = [Link]() # Read third column
print(third_line)
[Link]()

#readlines() method specifies the position


file = open('[Link]', 'r', encoding='utf-8')
print([Link]()[2]) # Read all rows in the file and specify the third row

[Link]()

8 - 14
Introduction to Computer Science (I) 8. File Processing

◼ python file processing method


 with open
When processing files, the with open syntax is commonly used to read or write files.
This syntax provides a concise and safe way to handle archives, avoiding resource leaks or errors that may
occur if you forget to close the archive manually. The syntax is: The following program
with open('file path', ‘mode', encoding=‘encoding') as file object: blocks must be indented.

If they are out of indentation,


# Read entire file close the file processor.
with open('[Link]', 'r', encoding='utf-8') as file:
content = [Link]()
print(content)

# Read file line by line


with open('[Link]', 'r', encoding='utf-8') as file:
for line in file:
print([Link]()) # strip() Remove the newline characters at the end of each line
8 - 15

You might also like