[英]passing variable to loop as string in 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'
我尝试了几种语法来尝试识别变量,但在网络上找不到足够类似的示例。 任何建议将不胜感激。
你有
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
的返回码。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.