Python 先读后写项目

Python Read then Write project

我正在尝试编写一个程序,该程序将读取一个文本文件并将其读取的内容转换为另一个文本文件,但使用给定的变量。有点像自制的加密。我希望程序一次读取 2 个字节并读取整个文件。我是 python 的新手,但很喜欢这个应用程序。任何帮助将不胜感激

一=12
b = 34
c = 56
等等...多达 20 种不同类型的变量

file2=打开("textfile2.text","w")
文件=打开("testfile.txt","r")
file.read(2):
如果 file.read(2) = 12 那么;
file2.write("a")
否则如果 file.read(2) = 34
file2.write("b")
否则如果 file.read(2) = 56
file2.write("c")
file.close()
file2.close()


文本文件看起来像:
1234567890182555

所以程序会读取 12 并将 "a" 写入另一个文本文件,然后读取 34 并将 "b" 写入另一个文本文件。只是有一些逻辑问题。

我喜欢你的想法,我会怎么做。请注意,我使用 lower() 将所有内容都转换为小写,但是如果您了解我在做什么,那么将其扩展为适用于小写和大写将非常简单:

import string

d = dict.fromkeys(string.ascii_lowercase, 0) # Create a dictionary of all the letters in the alphabet

updates = 0
while updates < 20: # Can only encode 20 characters
    letter = input("Enter a letter you want to encode or type encode to start encoding the file: ")
    if letter.lower() == "encode": # Check if the user inputed encode
        break
    if len(letter) == 1 and letter.isalpha(): # Check the users input was only 1 character long and in the alphabet
        encode = input("What do want to encode %s to: " % letter.lower()) # Ask the user what they want to encode that letter to
        d[letter.lower()] = encode
        updates += 1
    else:
        print("Please enter a letter...")

with open("data.txt") as f:
    content = list(f.read().lower())

for idx, val in enumerate(content):
    if val.isalpha():
        content[idx] = d[val]

with open("data.txt", 'w') as f:
    f.write(''.join(map(str, content)))

print("The file has been encoded!")

用法示例:

原文data.txt:

The quick brown fox jumps over the lazy dog

运行 脚本:

Enter a letter you want to encode or type encode to start encoding the file: T                                                                                                                                                                                          
What do want to encode t to: 6                                                                                                                                                                                                                                          
Enter a letter you want to encode or type encode to start encoding the file: H                                                                                                                                                                                          
What do want to encode h to: 8                                                                                                                                                                                                                                          
Enter a letter you want to encode or type encode to start encoding the file: u                                                                                                                                                                                          
What do want to encode u to: 92                                                                                                                                                                                                                                         
Enter a letter you want to encode or type encode to start encoding the file: 34                                                                                                                                                                                         
Please enter a letter...                                                                                                                                                                                                                                                
Enter a letter you want to encode or type encode to start encoding the file: rt                                                                                                                                                                                         
Please enter a letter...                                                                                                                                                                                                                                                
Enter a letter you want to encode or type encode to start encoding the file: q                                                                                                                                                                                          
What do want to encode q to: 9                                                                                                                                                                                                                                          
Enter a letter you want to encode or type encode to start encoding the file: encode                                                                                                                                                                                     
The file has been encoded!

编码data.txt:

680 992000 00000 000 092000 0000 680 0000 000

我会阅读源文件并将项目转换为字符串。然后将整个结果字符串分别写入第二个文件。这也将允许您使用更好的 with open 结构来读取文件。这允许 python 为您处理文件关闭。

此代码无效,因为它只读取前两个字符。您需要就如何迭代它创建自己的想法,但这里有一个想法(不只是为您制定解决方案)

with open("textfile.text","r") as f:
    # you need to create a way to iterate over these two byte/char increments
    code = f.read(2)
        decoded = <figure out what code translates to>
        results += decoded

# now you have a decoded string inside `results`

with open("testfile.txt","w") as f:
    f.write(results)

decoded = <figure out what code translates to> 部分可以比使用一堆串行 if/elseifs...

做得更好

也许定义一个编码字典?

codings = {
    "12": "a",
    "45": "b",
    #  etc...
    }

那么你可以:

results += codings[code]

而不是 if 语句(这样会更快)。