在python中读写文件,比较不同文件中的字符

2024-04-30 00:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中读取2个文件,然后基于这2个文件创建另一个文件。第一个文件包含常规英语(例如“hello”),第二个文件包含“密文”(2个5个字母的随机字符串ex“aiwld”和“pqmcx”),我想将字母“h”与密文中的第一个字母匹配,并将其存储在第三个文件中(我们创建的文件)

def cipher():
    file = english.txt
    file2 = secret.txt
    file3 = cipher.txt

    outputFile = open(file, 'r')
    outputFile = open(file2, 'r')

所以我有open,for reading,file and file2,我想匹配英文.txt第一个字母在机密.txt然后把那封信写给密码.txt文件。我完全不知道从哪里开始,任何帮助都会很好。在

我是否需要打开两个文件,从两个文件中读取,以某种方式进行比较然后写入文件? 我想我真的不确定如何将每个文件中的单个字母与另一个文件中的其他单独字母进行比较。在

我想我会想要一些类似布景的东西英文.txt[0]==机密.txt[0]但我不太确定。在


Tags: 文件字符串txthello字母open常规ex
2条回答

这里的关键是如何逐字符迭代文件(而不是更简单的逐行迭代)。在

最简单的解决方案是将这两个文件完全读入内存并一起迭代。这可以通过file.read()调用和zip()内置函数来完成。这是因为大文件会导致内存不足。在

写出结果只是一个正常的file.write()调用。在

例如:

with open('plaintext.text') as ptf:
    plaintext = ptf.read()
with open('key.txt') as keyf:
    key = keyf.read()

with open('output.txt') as f:
    for plaintext_char, key_char in zip(plaintext, key):
        # Do something to combine the characters
        f.write(new_char)

所以这可能太复杂了,但是

def cipher(file1 = 'english.txt',
       file2 = 'secret.txt',
       file3 = 'cipher.txt'):
fh1 = open(file1, 'r') # open the files
fh2 = open(file2, 'r')
fh3 = open(file3, 'w+') # write this file if it doesn't exist
ls1 = list() # initiate lists
ls2 = list()
for line in fh1: # add the charecters to the list
    for char in line:
        ls1.append(char)
for line in fh2:
    for char in line:
        ls2.append(char)
if ' ' in ls1: # remove blank spaces
    ls1.remove(' ')
if ' ' in ls2:
    ls2.remove(' ')

    print ls1, ls2

for i in range(len(ls1)): # traverse through the list and write things! :)
    fh3.write(ls1[i] + ' ' + ls2[i] + '\n')

相关问题 更多 >