File Processing - PowerPoint PPT Presentation

1 / 10
About This Presentation
Title:

File Processing

Description:

File Processing CMSC 120: Visualizing Information Lecture 4/15/08 Files in Python Binary Data are encoded in binary Metadata provides instructions for decoding and ... – PowerPoint PPT presentation

Number of Views:118
Avg rating:3.0/5.0
Slides: 11
Provided by: EmilyG161
Learn more at: https://cs.brynmawr.edu
Category:
Tags: data | file | processing

less

Transcript and Presenter's Notes

Title: File Processing


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
  • ltRETURNgt or ltENTERgt inputs a sequence of
    characters
  • end-of-line marker
  • newline
  • '\n
  • gtgtgt 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
  • ltfilenamegt open(ltnamegt, ltmodegt)
  • ltnamegt name of the file
  • ltmodegt 'r' or 'w'
  • gtgtgt infile open('mydata.txt', 'r')

7
Closing Files
  • ltfilenamegt.close()
  • infile.close()

8
Reading from Files
  • Read entire file into a single string
  • ltfilenamegt.read()
  • Read the next line of the file
  • ltfilenamegt.readline()
  • Read entire file into a list of lines
  • ltfilenamegt.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
  • ltfilenamegt.write(ltstringgt)
  • 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()
Write a Comment
User Comments (0)
About PowerShow.com