Python adds line break to unexpected place
本问题已经有最佳答案,请猛点这里访问。
我正在编写一个脚本,从文件中查找目录路径,以从中形成ant mkdir元素。
问题是,当我在末尾打印时,每行中都添加了换行符:
1 | ant_mkdir = '<mkdir dir="..' + path + '"/>' |
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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() |
打印结果:
1 2 3 4 5 6 | <mkdir dir="../path/folder/1 "/> <mkdir dir="../path/folder/2 "/> <mkdir dir="../path/folder/3 "/> |
尝试:
1 | ant_mkdir = '<mkdir dir="..' + path.rstrip() + '"/>' |
删除空白和换行符。