【Python-18】 File Input/Output

 

 第一节

     1 介绍了Python的文件操作函数open()

     2 比如f = open("out.txt" , "w")是表示打开可写的方式打开out.txt

     3 任何打开的文件都要进行close,比如f.close()

    

 第二节

     1 介绍了我们以"w"方式打开文件的write()函数

     2 比如f = open("out.txt" , "w")是表示打开可写的方式打开out.txt,然后我们f.write("haha")是把"haha"字符串写入到out.txt中

     3 练习:把my_list中的每一项都写到文件output.txt中,并且在每一项后面加上"\n"

my_list = [i**2 for i in range(1,11)]

my_file = open("output.txt", "r+")

# Add your code below!
for num in my_list:
    my_file.write(str(num)+"\n")
my_file.close()

 

 

 

 第三节

     1 介绍了我们以"r"方式打开文件的read()函数

     2 练习:以"r"方式打开output.txt,利用read()函数输出这些值

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

 

 

 

 第四节

     1 介绍了readline()函数用来读入一行

     2 练习:以"r"方式打开text.txt文件,然后输出三行读入的readline


# text.txt
I'm the first line of the file!
I'm the second line.
Third line here, boss.

# code
my_file = open("text.txt" , "r")

print my_file.readline()
print my_file.readline()
print my_file.readline()

my_file.close()

 

 

 第五节

     1 介绍了with...as...结构的使用

     2 with open("file","mode") as variable:
                # Read or write to the file

  

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值