Basic File Handling in Python: Reading and Processing Text Files
This guide covers basic file handling in Python, including creating a file object, reading contents, and processing each line within a file. Learn how to open a file using the `open` function, and how to iterate over lines in a text file using a for loop. We will explore line-based processing techniques, including stripping whitespace and splitting lines into tokens for further analysis. An example showcases how to handle a formatted text file and convert its contents into a structured list for easier manipulation.
Basic File Handling in Python: Reading and Processing Text Files
E N D
Presentation Transcript
Creative Computing Reading from Files
Opening a file • Create a file object and store it in a variable • <name> = open("<filename>") • Example: work_hrs = open("work.txt")
Line-based processing • A file can be a target in a for… in loop • for <var> in <file>: <var> = <var>.strip() # takes off white space • Example:for line in work_hrs: line = line.strip()
Split a line • Recall: strings can be split • If we have a text file that looks like: • 123 Susan 12.5 8.1 7.6 3.2 • We can split it into the list: • ['123', 'Susan', '12.5', '8.1', '7.6', '3.2‘] for line in work_hrs:line = line.strip() tokens = line.split()