python用open语句打开的文件位置_python – 如何使用open with语句打开文件

Python允许将多个open()语句放在一个单独的。你可以用逗号分隔。您的代码将是:

def filter(txt, oldfile, newfile):

'''\

Read a list of names from a file line by line into an output file.

If a line begins with a particular name, insert a string of text

after the name before appending the line to the output file.

'''

with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:

for line in infile:

if line.startswith(txt):

line = line[0:len(txt)] + ' - Truly a great person!\n'

outfile.write(line)

# input the name you want to check against

text = input('Please enter the name of a great person: ')

letsgo = filter(text,'Spanish', 'Spanish2')

不,你不会通过在函数结束时显式返回来获得任何东西。你可以使用return提前退出,但是你在结束时,函数将退出而没有它。 (当然有返回值的函数,你使用return指定要返回的值。)

在引入了with语句时,或者在Python 2.6中,在Python 2.5中不支持使用多个open()项目,但在Python 2.7和Python 3.1或更高版本中支持。

如果你正在编写必须在Python 2.5,2.6或3.0中运行的代码,请嵌套with语句作为建议的其他答案或使用contextlib.nested。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值