files. - gramercydataappending data to an existing file dumas2.txt assignment: writing numeric data...

Post on 20-Sep-2020

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

AgendaThree Steps to Working With Files:

1. Open the file for reading or writing (appending).2. Read / Write.3. Close.

Three File Access Methods:

1. ‘r’ - Open a file for Reading only.2. ‘w’ - Writing. If the file already exist, erase it.

Create if it does not exist. 3. ‘a’ - Append to the end of the file. If it does not

exist, create it.

Specifying the location of a file.1. The file is created in the same folder as the script:

test_file = open (‘test.txt’, ‘w’)

2. You can specify a path as well as a filename. Use raw string to read the backslash characters as literal backslashes.

test_file = open (r‘C:\Users\Blake\Proj\test.txt’, ‘w’)

Writing data to a file

dumas.txt

Reading data from a file

Program output

Read one line at a time

Program output includes an extra blank line.readline() returns a string that ends with ‘\n’.

Concatenating a newline to a stringThis program writes three lines of text from three strings.

dumas2.txt

Appending data to an existing file

dumas2.txt

Assignment: writing numeric data

Solution

Reading numeric data: program output

Reading numeric data

6.2 Using Loops to Process Files

Program write_sales.py

Program output

sales.txt

Program: read_sales.py

sales.txt

Program output

the readline() method returns an empty string ‘’ when it has attempted to read beyond the end of a file. This makes it possible to write a while loop that determines when the end of a file has been reached.

Version 2 of the same program: read_sales2.pyThis for loop automatically reads line in a file without testing for any special condition that signals the end of the file.

top related