首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将输出保存到新的文本文件中?

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

Stack Overflow用户
提问于 2015-03-16 23:00:05
回答 1查看 75关注 0票数 0

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

感谢所有未来的帮助。

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-16 23:08:05

我不知道你的代码到底是怎么回事。

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

代码语言:javascript
复制
with open('output.txt', 'w+') as new_file:
    new_file.write(variable)

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

如果是txt_list中想要写入该文件的所有项目,我不认为我会首先对它们进行join。只需使用for循环:

代码语言:javascript
复制
with open('output.txt', 'w+') as new_file:
    for item in txt_list:
        new_file.write(item) 

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

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29088467

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档