如何将输出保存到新文本文件中?

时间:2015-03-16 23:00:06

标签: python

所以基本上,我有一个超长输出,我希望能够将此输出保存到一个全新的文本文件,而无需更改我的旧文件。这是我到目前为止的代码,我基本上只需要知道如何处理我的out_file变量。

感谢所有未来的帮助。

txt_list = []

with open("X:\- Photogrammetry\Python to Correct DXF Colors\InvolvedPontiac.dxf", "r") as in_file, open("X:\- Photogrammetry\Python to Correct DXF Colors\InvolvedPontiacfixed.txt", "w+") as new_file:
    for line in in_file:
        line = line.rstrip()
        txt_list.append(line)
Entity = 0
i = 0
while i < len(txt_list):
    if txt_list[i] == "ENTITIES":
        Entity = 1
    if txt_list[i] == " 62" and Entity == 1:
        txt_list[i+1] = " 256"
    i += 1


Layer = 0
j = 0
while j < len(txt_list):
    if txt_list[j] == "LAYER" and txt_list[j+2] != " 7":
        Userinput = input("What color would you like for the layer " +txt_list[j+2] + "? Type 0 for black, 1 for red, 3 for green, 4 for light blue, 5 for blue, 6 for magenta, 7 for white, 8 for dark grey, 9 for medium gray, or 30 for orange.")
        txt_list[j+6] = " " + Userinput

        print ("The " + txt_list[j+2] + " layer now has a color code of " + Userinput)
    j += 1
for item in txt_list:
    new_file.write(item)
print ('\n'.join(txt_list))

1 个答案:

答案 0 :(得分:1)

我不确定您的代码到底发生了什么。

但是要将变量写入文件,可以使用

with open('output.txt', 'w+') as new_file:
    new_file.write(variable)

请注意,如果文件不存在,'w+'将创建该文件,如果文件存在,则会覆盖该文件。

如果txt_list中的所有项目都要写入该文件, 我不认为我先join他们。只需使用for循环:

with open('output.txt', 'w+') as new_file:
    for item in txt_list:
        new_file.write(item) 

这将打印该列表中文件中新行的每个项目。

txt_list = []

with open("X:\- Photogrammetry\Python to Correct DXF Colors\InvolvedPontiac.dxf", "r") as in_file:
    for line in in_file:
        line = line.rstrip()
        txt_list.append(line)
Entity = 0
i = 0
while i < len(txt_list):
    if txt_list[i] == "ENTITIES":
        Entity = 1
    if txt_list[i] == " 62" and Entity == 1:
        txt_list[i+1] = " 256"
    i += 1


Layer = 0
j = 0
while j < len(txt_list):
    if txt_list[j] == "LAYER" and txt_list[j+2] != " 7":
        Userinput = input("What color would you like for the layer " +txt_list[j+2] + "? Type 0 for black, 1 for red, 3 for green, 4 for light blue, 5 for blue, 6 for magenta, 7 for white, 8 for dark grey, 9 for medium gray, or 30 for orange.")
        txt_list[j+6] = " " + Userinput

        print ("The " + txt_list[j+2] + " layer now has a color code of " + Userinput)
    j += 1

with open('output.txt', 'w+') as new_file:
    for item in txt_list:
        new_file.write(item)

print ('\n'.join(txt_list)
相关问题