Python为意想不到的地方增加了换行符

时间:2014-05-14 12:06:12

标签: python python-2.7

我正在制作脚本以从文件中查找目录路径,从而形成ant mkdir元素。

问题是,当我最后打印时,每行内都添加了换行符:

ant_mkdir = '<mkdir dir="..' + path + '"/>'

代码:

from io import open
from string import *
def main():
    with open("file.txt", "r") as f:
        content = f.readlines()

    paths = []
    for line in content:
        if ("d:\\apps" in line):
            line = line.split("d:\\apps")
            path = line[1]
            path = path.replace("\\", "/")
            if path not in paths:
                paths.append(path)

    for path in paths:
        ant_mkdir = '<mkdir dir="..' + path + '"/>'
        print ant_mkdir

if __name__ == "__main__":
    main()

打印结果:

<mkdir dir="../path/folder/1
"/>
<mkdir dir="../path/folder/2
"/>
<mkdir dir="../path/folder/3
"/>

1 个答案:

答案 0 :(得分:1)

尝试:

 ant_mkdir = '<mkdir dir="..' + path.rstrip() + '"/>'

删除空格和换行符。