CP104 Lecture Notes - Lecture 8: Gnu Readline, For Loop

63 views3 pages
School
Course
Professor
Files
- First step: open file
- E.g file_handle(whatever name)=open(filename,mode,encoding)
- USE OPEN
- file_handle=’
- close() to close file at the end data may be lost if not closed
- By default it reads
- For loop for files is like a list of strings
- Eg. for line in myfile:
- 1) open the file
- 2) process the file
- 3) close the file
- mode=’r’
- ‘W’ write in file
- ‘A’ cursor at the end file
- \n at the end of lines of string there counts as a number (file processing SLIDE)
- \n counts as one letter, not 2
- For line in myfile:--->deals as list of strings
- readline() method advances cursor to where we are reading
- Read line till ‘\n’
- To count words: how many words or letters? For loop
READING WHOLE FILE AS A SINGLE STRING
-
- readlines()
- User for loop and handle
Have to convert to string when writing in a file
- e.g myfile.write(str(4))
Can't do two for loops because the cursor is at the bottom after first for loop:
-instead put it i a list
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in
hayjayshay and 38575 others unlocked
CP104 Full Course Notes
2
CP104 Full Course Notes
Verified Note
2 documents

Document Summary

Use open file_handle=" close() to close file at the end data may be lost if not closed. For loop for files is like a list of strings. Eg. for line in myfile: open the file, process the file, close the file. \n at the end of lines of string there counts as a number (file processing slide) For line in myfile:--->deals as list of strings. Read line till \n" readline() method advances cursor to where we are reading. Reading whole file as a single string readlines() Have to convert to string when writing in a file e. g myfile. write(str(4)) Can"t do two for loops because the cursor is at the bottom after first for loop: When an existing file is opened, the w" mode erases the contents of the file. When opening the file with append the cursor is located at the end of the file. Prints backlash so if 6 lines 12 will be printed.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents

Related Questions