Fu Fundamentals of Pr Programming (Py Python)
File Processing
Ali Taheri Sharif University of Technology
Spring 2019
File Processing Ali Taheri Sharif University of Technology Spring - - PowerPoint PPT Presentation
Fu Fundamentals of Pr Programming (Py Python) File Processing Ali Taheri Sharif University of Technology Spring 2019 Outline 1. Sources of Input 2. Files 3. Opening a File 4. Opening Modes 5. Closing a File 6. Writing to a File 7.
Spring 2019
2
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
3
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
1. Open the file 2. Read or write (perform operation) 3. Close the file
4
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
5
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
f = open('output.txt', 'w') f = open('C:/Python36/README.txt', 'r')
6
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
Mode Description
‘r’
Open a file for reading (default).
‘w’
Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
‘a’
Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
‘b’
Open in binary mode.
‘+’
Open a file for updating (reading and writing)
f = open("test.txt") # equivalent to 'r' f = open("test.txt",'r+') # read from begin, write at end f = open("img.bmp",'wb') # write in binary mode
7
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
f = open('output.txt', 'w') # some operations here f.close() with open('data.txt', 'a+') as f: # some operations here # now the file has been closed
lines.
8
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
with open('data.txt', 'w') as f: f.write("my first file\n") f.write("This file\n\n") f.write("contains four lines\n") print('Sample text', file=f)
9
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
10
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
with open('input.txt', 'r') as f: s = f.read(10) # read 10 characters s = f.read() # read to the end of file S = f.readline() # read the next line
11
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
with open('input.txt', 'r') as f: lines = f.readlines() # returns all lines as a list for line in f: print(line, end='')
12
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
import pickle var = [(1, 'x', [3,4]), {1,2,3}] with open(‘file.txt', ‘wb') as f: pickle.dump(var, f) # Writes “var” to “file.txt” with open(‘file.txt', ‘rb') as f: print(pickle.load(f)) # Reads the variable in “file.txt”