Download presentation
Presentation is loading. Please wait.
Published byRoberta Hines Modified over 8 years ago
1
File Processing CMSC 120: Visualizing Information Lecture 4/15/08
2
Files in Python Binary Data are encoded in binary Metadata provides instructions for decoding and encoding file Plain text Data converted to text Text converted to numerical representation Numerical code saved to file One really long string
3
Multi-Line Processing or inputs a sequence of characters end-of-line marker newline '\n‘ >>> print 'Hello\nWorld' Hello World
4
Escape Sequences '\n' : newline '\t' : tab '\\' : \ '\'' : ' '\"' : " '\a' : ASCII bell ● '\b' : ASCII backspace '\uXXXX' : chr with UNICODE XXXX
5
File Processing Open the file Associate the file with a name Manipulate the file Read or Write Close the file Disassociate from Name Files are Objects
6
Opening Files = open(, ) = name of the file = 'r' or 'w' >>> infile = open('mydata.txt', 'r')
7
Closing Files.close() infile.close()
8
Reading from Files Read entire file into a single string.read() Read the next line of the file.readline() Read entire file into a list of lines.readlines()
9
Reading from a File # read and display # first 5 lines of a file infile = open(someFile, 'r') for i in range(5): line = infile.readline() print line[:-1] infile.close()
10
Writing to a File Just like using the print statement.write( ) # write two lines to a file outfile = open('mydata.txt', 'w') count = 1 outfile.write('This is the first line\n') count = count + 1 outfile.write('This is line number %d.' % count) outfile.close()
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.