读取和打印多个文件到一个outfile

时间:2016-12-10 00:28:09

标签: python file io

通过我的文件阅读和打印时,通过我的cousole打印给我正确的结果,但写入outfile不

#IMPORT STUFF
import pyglet as pg
from random import randint

mouse = pg.window.mouse

#VARS
window = pg.window.Window(width = 640, height = 480)
score = 0
circleImg = pg.image.load("circle.png")
circle = pg.sprite.Sprite(circleImg, randint(1, window.width), randint(1, window.height))
text = pg.text.Label("Click red!", font_name = "Times New Roman", font_size = 18, x = 260, y = 10)


#DETECT MOUSE PRESS ON CIRCLE
@window.event
def on_mouse_press(x, y, button, modifiers):
    if x == circle.x and y == circle.y:
        circle.x = randint(1, window.width)
        circle.y = randint(1, window.height)

@window.event
def on_draw():
    window.clear()
    text.draw()
    circle.draw()

pg.app.run()

这会打印出我输入的所有字母

with infile as f :
    lines = f.readlines()

new_line = " "

for line in lines:
    new_line = ''.join(line).replace('*',letter.upper())
    new_line = new_line.replace(':',letter.lower())
    print(new_line)

它只给我输入单词的最后一个字母。

with infile as f :
    lines = f.readlines()

new_line = " "

for line in lines:
    new_line = ''.join(line).replace('*',letter.upper())
    new_line = new_line.replace(':',letter.lower())
    outfile.write(new_line)

这是我目前正在使用的代码。我从txt文件中获取符号并根据用户输入的内容将其更改为共鸣信

2 个答案:

答案 0 :(得分:0)

在循环之前打开输出文件而不是在其中:

outfile = open("word_art.txt", "w")
for letter in word:

答案 1 :(得分:0)

with open("test.txt",'r') as f :
lines = f.readlines()

with open('out.txt','w') as outfile: 
    for line in lines:
        new_line = line.replace('*',letter.upper())
        new_line = new_line.replace(':',letter.lower())
        outfile.write(new_line)

这对我有用。

编辑: TigerhawkT3是正确的。我检查了你的完整代码,你在循环内一次又一次地打开文件,每次都丢弃先前的更改。