基本上,我有一个超长的输出,我希望能够将这个输出保存到一个全新的文本文件中,而不需要更改我的旧文件。到目前为止,这是我的代码,我基本上只需要知道如何处理我的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))发布于 2015-03-16 23:08:05
我不知道你的代码到底是怎么回事。
但是要将变量写入文件,可以使用
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)https://stackoverflow.com/questions/29088467
复制相似问题