在Python中将变量作为字符串传递给循环
我有一个Python脚本,它会处理一个文件夹里的每个文件,逐个查看文件的内容,并为每个输入文件创建一个输出文件。这个输出文件可能会有重复的内容,如果有的话,我希望只保留独一无二的值,就像UNIX命令那样。
uniq -u input.file > output.file
虽然我可以用shell脚本来完成这个任务,但我想在Python中加一行代码,只保留独特的值。我知道我可以这样做:
import os
os.system("uniq -u input.file > output.file")
不过,当我试着把这段代码放进一个循环里,以便处理我刚刚生成的所有文件时:
for curfile in fs:
if curfile[-3:]=='out':
os.system("uniq -u %s > %s") % (str(curfile), str(curfile[:-4] + ".uniq")
我遇到了以下错误:
unsupported operand type(s) for %: 'int' and 'tuple'
我尝试了几种语法来让变量被识别,但在网上找不到类似的例子。任何建议都会非常感谢。
1 个回答
3
你有
os.system(
"uniq -u %s > %s"
) % ( # The % and this paren should be inside the call to os.system
str(curfile),
str(curfile[:-4] + ".uniq")
# you're missing a close paren here
你需要
os.system(
"uniq -u %s > %s" % (
str(curfile),
str(curfile[:-4] + ".uniq")
)
)
首先,你要格式化这个字符串,然后再把它传给 os.system
-- 现在的做法是,字符串先传给 os.system
,然后你再试着用 %
来处理结果,而这个结果是一个 int
类型的数字。(也就是 uniq
的返回码。)