Python 我需要使用format方法将未知数量的参数替换为文本文件
Python 我需要使用format方法将未知数量的参数替换为文本文件,python,file,text,format,Python,File,Text,Format,pagesubs()函数将文本文件读入字符串,然后使用Python的format()替换subs参数中给定的参数 以下是示例: 我的尝试如下: def pagesubs(N,*subs): assert type(N)==str F= open(N,'r') return F.format(subs) 我得到一个错误,F是type(file),但我认为open()将文本文件读入字符串。非常感谢您的帮助 编辑:示例 pagesubs('index.html', 'Dec
pagesubs()
函数将文本文件读入字符串,然后使用Python的format()
替换subs参数中给定的参数
以下是示例:我的尝试如下:
def pagesubs(N,*subs):
assert type(N)==str
F= open(N,'r')
return F.format(subs)
我得到一个错误,F是type(file)
,但我认为open()
将文本文件读入字符串。非常感谢您的帮助
编辑:示例
pagesubs('index.html', 'December', 18, 2012)
This will return the content of the file index.html, but
with "December" substituted for {0}, and 18 substituted
for {1}, and 2012 substituted for {2}.
您需要对文件调用
read()
函数,以便将其内容转换为字符串。请尝试以下代码:
def pagesubs(N, *subs):
assert type(N)==str
with open(N,'r') as F:
content = F.read()
return content.format(subs)
您需要添加
.read()
或.readlines()
来实际读取文件。Open()
只返回一个文件对象,您需要在该对象上使用一些其他函数来读取文本,阅读更多就可以了。。。对不起,我是个编程高手