Python学习——读取文件

1、open()函数用于打开一个文件

with open("pi_digits.txt") as file_object:
    contents = file_object.read()
    print(contents)

 

2、还可以按行来读取文件里的内容

file_name = "pi_digits.txt"

with open(file_name) as file_object:
    for line in file_object:
        print(line)

 

3、open()返回的文件只能在with代码块里使用,如果要在外部使用要将文件内保存在一个列表中。之后用for循环将列表里的数据赋给一个变量,就可以使用了。

file_name = "pi_digits.txt"
with open(file_name) as file_object:
    lines = file_object.readlines()
    
pi_string = ""
for line in lines:
    pi_string = pi_string + line.strip()

print(pi_string)
print(len(pi_string))

 

4、将一个文件里的“c”都替换为“python”

file_name = "c.txt"
with open(file_name) as file_object:
    lines = file_object.readlines()
    
source_string = "c"
target_string = "Python"

text = ""
for line in lines:
    if source_string in line:
        line = line.replace(source_string, target_string)
    text = text + line.strip()

print(text)
print(len(text))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值