2015-03-08 2 views
0

Итак, я пытаюсь написать сценарий, который принимает два файла и изменяет первый, прежде чем записывать его в предел назначения, но всякий раз, когда я его запускаю, скрипт печатает только первую измененную строку и снова.Бесконечная петля при открытии файла

#3a 
def modify(string): 
    """Takes a string and returns a modified version of the string using two modifications. One must be a replacement of some kind. 

    string -> string""" 
    while string != "": 
     string = string.upper() 
     string = string.replace("A","4").replace("B","8").replace("C","<").replace("E","3").replace("G","6").replace("I","1").replace("O","0").replace("R","|2").replace("S","5").replace("T","7").replace("Z","2") 
     print(string) 

#3b - asks the user to type in a source code filename and destination filename; opens the files; loops through the contents of the source file line-by-line, using modify() to modify eat line before writing it to the destination file; the closes both files. 
source = input("What file would you like to use?") 
destination = input("Where would you like it to go?") 
filesource = "" 

while filesource == "": 
    try: 
     file_source = open(source, "r") 
     file_destination = open(destination, "w") 
     for item in file_source: 
      mod = modify(item) 
      file_destination.write(mod) 
     file_source.close() 
     file_destination.close() 
     break 
    except IOError: 
     source = input("I'm sorry, something went wrong. Give me the source file again please?") 

Любая помощь?

+4

и как, вы думаете, 'string' становится пустой строкой в ​​цикле в то время? – Daniel

+3

Точно так же, как вы думаете, 'filesource' никогда не будет пустым, когда вы никогда ничего не присваиваете ему? – poke

+0

Я думаю, вы путаете 'if' с' while'. И ваше использование 'filesource' выглядит как тип для предполагаемого' file_source'. – user1016274

ответ

0

Подсказка: если вы запустите modify("TEST ME"), что он вернет?

Добавить return string в конец modify функция.

0

Строка никогда не опустошает - попробуйте разбора через него обугливается по полукокса с использованием индекса Int и ваш условный быть while i < len(string)

Смежные вопросы