Codeacademy Python-12-File Input/Output

来源:互联网 发布:淘宝会员等级v6 编辑:程序博客网 时间:2024/06/05 18:37

在Codeacademy上学习Python课程,刷题的笔记记录如下,欢迎交流!

    • 目录
    • Good Morning Class
      • See it to Believe it
      • The open Function
      • Writing
      • Reading
    • The Devils in the Details
      • Reading Between the Lines
      • PSA Buffering Data
      • Sending a Letter
      • Try It Yourself
      • Case Closed

目录

1. Good Morning Class!

1.See it to Believe it

#以可写的方式打开output.txt,若没有则创建,然后写文件my_list = [i**2 for i in range(1,11)]# Generates a list of squares of the numbers 1 - 10f = open("output.txt", "w")for item in my_list:    f.write(str(item) + "\n")f.close()

2.The open() Function

# "r+" = the file will allow you to read and write to it! my_file = open("output.txt","r+")

3.Writing

my_list = [i**2 for i in range(1,11)]# Generates a list of squares of the numbers 1 - 10my_file = open("output.txt", "w")for item in my_list:    my_file.write(str(item) + "\n")my_file.close()

4.Reading

my_file =open("output.txt","r")print my_file.read()my_file.close()

2. The Devil’s in the Details

5.Reading Between the Lines

#按行读取,一次一行my_file = open("text.txt", "r")print my_file.readline()print my_file.readline()print my_file.readline()my_file.close()

6. PSA: Buffering Data

## Open the file for readingread_file = open("text.txt", "r")# Use a second file handler to open the file for writingwrite_file = open("text.txt", "w")# Write to the filewrite_file.write("Not closing files is VERY BAD.")write_file.close()

7. Sending a Letter

#with ... as ... 操作 with open("text.txt", "w") as textfile:    textfile.write("Success!")

8.Try It Yourself

with open("text.txt","w") as my_file:    my_file.write("Write a word!")

9.Case Closed?

#如果没有关闭,则关闭with open("text.txt","w") as my_file:    my_file.write("Write a word!")if my_file.closed == False:    my_file.close()print my_file.closed
0 0
原创粉丝点击