Python:为什么我的程序不能从列表中写入文件?

时间:2014-03-08 16:39:42

标签: python

我有一个txt文件的线索,例如A是#,B是?,C是@等。

我正在尝试读取密文文件,并使用我已导入列表的线索的txt文件交换密码符号。

出于某种原因,它不会按预期执行我的替换。

def Import_Clues_to_Lists():
global letter_list
global symbol_list
file_clues=open('clues.txt','r')
for line in file_clues:
    for character in line:
        if character.isalpha() == True:
            letter_list[int(ord(character)-65)]  = line[0]
            symbol_list[int(ord(character)-65)] = line[1]
file_clues.close()


def Perform_Substitution():
Import_Clues_to_Lists()
print(letter_list)
print(symbol_list)
file_words = open('words.txt','r')
temp_words = open('wordsTEMP.txt','w')
for line in file_words:
    for character in line:
        if character.isalpha() == False:
            position = symbol_list.index(character) # get the position for the list
            equivalent_letter = letter_list[position] # get the equivalent letter
            temp_words.write(equivalent_letter) # substitute the symbol for the letter in the temp words file.
        else:
            temp_words.write(character)
file_words.close()
temp_words.close()
import os # for renaming files
#os.remove('words.txt')
#os.rename('wordsTEMP.txt','words.txt')
menu()

我的逻辑错误的任何想法?

1 个答案:

答案 0 :(得分:1)

如果使用字典来保存符号及其代表的字符 - 替换字典,可能会更好。它将使您的代码更具可读性,从而更容易找到问题。

如果clues.txt看起来像这样:

a!
b#
c$
d%

尝试这些:

def Import_Clues_to_Lists():
    '''Create a substitution dictionary

    returns dict, {symbol : character}
    '''
    sub = dict()
    with open('clues.txt','r') as file_clues:
        for line in file_clues:
            # symbol = line[1], letter = line[0]
            sub[line[1]] = line[0]
    return sub

def Perform_Substitution():
    '''Iterate over characters of a file and substitute letters for symbols.

    creates a new file --> wordsTEMP.txt

    returns None
    '''
    # substitute is a dictionary of {symbol : character} pairs
    substitute = Import_Clues_to_Lists()
    for sym, char in substitute.items(): print(sym, char)
    with open('words.txt','r') as file_words, open('wordsTEMP.txt','w') as temp_words:
        for line in file_words:
            for character in line:
                if character in substitute:
                    character = substitute[character]
                temp_words.write(character)