在Codeacademy上学习Python课程,刷题的笔记记录如下,欢迎交流!
目录
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 - 10
f = 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 - 10
my_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 reading
read_file = open("text.txt", "r")
# Use a second file handler to open the file for writing
write_file = open("text.txt", "w")
# Write to the file
write_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