如何使用Python将相同的字符串常数应用于多个浮点值



我在一个文件中有一系列值,我想使用python脚本将两个"描述符"添加到所有一系列值。

示例:

值:

1 2 3  
1 3 4

描述符:

Ford truck

最终结果:

1 2 3 Ford truck  
1 3 4 Ford truck

我感谢任何帮助。我看过Hstack,但不确定这是最好的方法。

假设原始文件的名称是 fname,并且输出文件的名称应为 outputFile,您可以这样做:

with open(fname) as inputFile:
    content = inputFile.readlines()
    content = [x.strip() + "Ford truck" for x in content]
    with open(ofname, "w") as outputFile:
        for item in content:
            outputFile.write("%sn" % item) 

此代码将读取您原始输入文件的所有行,删除所有尾随的空白,将Ford truck添加到每行中,并将结果保存在输出文件中。

最新更新