滑铁卢大学学习资料module10

上传人:n**** 文档编号:57511874 上传时间:2018-10-22 格式:PDF 页数:34 大小:103.44KB
返回 下载 相关 举报
滑铁卢大学学习资料module10_第1页
第1页 / 共34页
滑铁卢大学学习资料module10_第2页
第2页 / 共34页
滑铁卢大学学习资料module10_第3页
第3页 / 共34页
滑铁卢大学学习资料module10_第4页
第4页 / 共34页
滑铁卢大学学习资料module10_第5页
第5页 / 共34页
点击查看更多>>
资源描述

《滑铁卢大学学习资料module10》由会员分享,可在线阅读,更多相关《滑铁卢大学学习资料module10(34页珍藏版)》请在金锄头文库上搜索。

1、Module 10: File input and OutputTopics: File input and outputReadings: ThinkP 8, 12, 14CS116 Fall 2014110: File input and outputScreen output and keyboard inputOur programs get their data from function parameter values, state variables declared in our program, or data entered by the user at the keyb

2、oard and have displayed results to the screen.Programs reading information from or writing to a file would be quite useful.CS116 Fall 201410: File input and output2Input/Output beyond the screen Computers store data in files Files are persistent: data exists after your program ends Files created by

3、one program can be used by other programs We will see how our programs can read input from files instead of from the keyboard write results to files instead of to the screenCS116 Fall 201410: File input and output3Creating a Text File for Reading In CS116, we are working with text files only. How to

4、 create a text file? In an editor, save as a text file Wing IDE, “save as“ - choose option for “plain text“ Not: .doc, .docx, .pdf, .rtf These are all binary formats. Any editor can be used to read/edit a plain text file.CS116 Fall 201410: File input and output4Pattern for using a file in Python Fin

5、d the file Open the file Access the file Write to the file, or Read from the file Cannot read from a file being written to Cannot write to a file being read from Close the fileCS116 Fall 201410: File input and output5Step 1: Finding a file Easiest Solution: ensure that the file being accessed is in

6、the same folder as the program using it (the active folder or directory) More general solution os module contains functions for interacting with the computers operating system os.getcwd() ? name of current directory os.listdir(os.getcwd() ? list of names of files in current directory os.chdir(dir_na

7、me) ? changes the current directory to the name given by dir_nameCS116 Fall 201410: File input and output6Step 2: Opening a file file module gives us access to files in the current directory file(filename, “r“) or file(filename) opens the file named filename for reading file(filename, “w“) creates t

8、he file named filename for writing. Warning! If there is already a file named filename, its contents are erased before the new data is written. Be careful!CS116 Fall 201410: File input and output7Step 3: Accessing files - reading f.readline() Returns the next line from file f Includes newline charac

9、ter Returns the empty string when at end of file f.readlines() Returns a list of strings containing each line from file f Each string terminates with newline character (if present in file) If file is very large, this may consume a lot of memoryCS116 Fall 201410: File input and output8Example: Proces

10、sing a file of namesSuppose you have a file containing a collection of names, where each line contains a single name in the form first_name (spaces) last_nameWrite Python code to create a list of Name objects from the open file object called names.CS116 Fall 201410: File input and output9A useful he

11、lper functionclass Name: fields: first, last def _init_(self, fn, ln): self.first = fn self.last = ln# str_name: String - Name # produces Name from s, where s has the # form “first last“ or “first lastn“ # s may include extra whitespace def str_name(s): nameslist = s.split() return Name(nameslist0,

12、nameslist1)CS116 Fall 201410: File input and output10Example: Solution One Read and convert one name at a time next_str = names.readline() people = while (next_str != “): next_name = str_name (next_str) people.append(next_name) next_str = names.readline()CS116 Fall 201410: File input and output11Exa

13、mple: Solution Two Read all lines, then convert all stringsall_names = names.readlines() people = map(str_name,all_names)CS116 Fall 201410: File input and output12Step 3: Accessing files - writing f.write(s) Appends the string s to the end of file f Writes the newline character only if s includes it

14、 f.writelines(los) Appends all the strings in los to the end of file f Writes newline characters only for those strings in los which include it Recall: If you open an existing file for writing, you lose the previous contents of that file.CS116 Fall 201410: File input and output13Example: Write Names

15、 in the form last_name, first_name# Continuing example out_file = file(“reversed.txt“,“w“) for p in people: out_file.write(“%s, %sn“ % (p.last, p.first)CS116 Fall 201410: File input and output14Step 4: Closing files f.close() Closes the file f If you forget to close a file after writing, you may los

16、e some data You can no longer access a file after it has been closedCS116 Fall 201410: File input and output15Template for reading from a fileinput_file = file(filename, “r“) # read file using # input_file.readline() # in a loop, or # input_file.readlines() # Note: resulting strings # contain newline input_file.close

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 高等教育 > 其它相关文档

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号