如何在函数中传递文件名

时间:2017-07-31 18:52:47

标签: python

我想传递.txt文件以在rot 13中加密,我如何传递.txt文件而不必硬编码我要加密的单词?这是我到目前为止所做的。

from string import maketrans

rot13Translate =maketrans 
('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')

def rot13(text):
    return text.translate(rot13Translate)

def main():
    txt = ("Hello World")
    print rot13(txt)

if __name__ == "__main__":
    main()

3 个答案:

答案 0 :(得分:0)

假设您将"your_file.txt"中的内容放在与脚本相同的目录中,您可以执行以下操作:

def main():
    with open("your_file.txt", "r") as f:
        txt = f.read()
        print rot13(txt)

不需要修改其余代码。

答案 1 :(得分:0)

假设您的文字位于encrypted_file.txt

def main(infilepath):
    with open(infilepath) as infile:
        for line in infile:
            ciphertext = line.strip()
            cleartext = rot13(ciphertext)
            print cleartext

main("encrypted_file.txt")

答案 2 :(得分:0)

您只需要在python中读取文件内容,如下所示:

txtFile = open(path_to_text_file, 'r').read()

然后将内容传递给翻译函数。以下是完整的代码:

from string import maketrans

rot13Translate = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')

def rot13(text):
    return text.translate(rot13Translate)

def main(txtFile):
    print rot13(txtFile)

if __name__ == "__main__":
    txtFile = open(path_to_text_file, 'r').read()
    main(txtFile)
相关问题