Codeacademy Python-12-File Input/Output

本文通过实际案例介绍了Python中文件输入输出的基本操作,包括文件的打开与关闭、读写方式的选择及具体应用,适合初学者实践参考。

在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值