jadon
Uploaded by
4 SLIDES
195 VUES
40LIKES

Basic File Handling in Python: Reading and Processing Text Files

DESCRIPTION

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.

1 / 4

Télécharger la présentation

Basic File Handling in Python: Reading and Processing Text Files

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript

Playing audio...

  1. Creative Computing Reading from Files

  2. Opening a file • Create a file object and store it in a variable • <name> = open("<filename>") • Example: work_hrs = open("work.txt")

  3. 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()

  4. 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()

More Related