文件加密---使用换位加密和解密方法加密文件
python可以从硬盘直接打开和读取文件
读取文件
读进变量
关闭文件
注意程序中的注释,是关于python的学习笔记。尽管看起来有点乱。。。
结合transpositionEncrypy and decrypy(https://www.cnblogs.com/PiaYie/p/13469532.html)的两个程序
# Transposition Cipher Encrypt/Decrypt File # http://inventwithpython.com/hacking (BSD Licensed) # time模块和time.time()函数 # 返回一个浮点数,是1970年1月1日起到现在的秒数 called "Unix Epoch" # 我们可以用两次调用time.time()的返回值来判断程序的运行时间 密码学是重视时间的 import time, os, sys, transpositionEncrypt, transpositionDecrypt def main(): #inputFilename = 'D:\\PiaYie\\jczhang\\密码学\\py密码学编程教学代码\\frankenstein.txt' inputFilename = 'frankenstein.txt' # BE CAREFUL! If a file with the outputFilename name already exists, # this program will overwrite that file. outputFilename = 'frankenstein.encrypted.txt' myKey = 10 myMode = 'encrypt' # set to 'encrypt' or 'decrypt' # If the input file does not exist, then the program terminates early. if not os.path.exists(inputFilename): print('The file %s does not exist. Quitting...' % (inputFilename)) sys.exit() # If the output file already exists, give the user a chance to quit. # 打开文件要当心 以'w'打开时,这个文件若已经存在会被删除再新建,即有一个内容清空的过程 # 但是我们有对策,os.path.exists(filename) 返回True or False,来检查某个文件名是否存在,可加上路径检查 if os.path.exists(outputFilename): print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % (outputFilename)) response = input('> ') # startswith()和endswit()返回True or False,字面意思 # 'hello'.startswith('h') ---> True 'hello'.startswith('he') ---> True if not response.lower().startswith('c'): sys.exit() # Read in the message from the input file # open()函数 第一个参数是文件的名字,同路径写名字即可,或者是绝对路径 # 路径 windows:D:\\PiaYie\\jczhang\\密码学\\py密码学编程教学代码\\frankenstein.txt # linux: /usr/piayie/frankenstein.txt # open()函数返回一个“文件对象” 数据类型 的值 用这个值标记一个文件,用于读取写入和关闭 # 第二个参数可选 默认'r'即读取打开 'w'---写入打开, 'a'---追加打开 # read()方法返回一个字符串包含文件里的所有内容,如果文件是多行的,则read()返回的这个字符串 # 每一行里都有一个\n换行字符 # close()方法 这个文件使用完毕就该关闭释放资源了 当然,py程序终止时候会自动释放所有未释放的资源 # 若希望重新读取文件,也要先行close() 再调用open() fileObj = open(inputFilename) content = fileObj.read() fileObj.close() #字符串的title()方法 #lower()转化为小写 upper()转化为大写 title()字符串中的每个单词的首字母大写,其他字母小写 print('%sing...' % (myMode.title())) # Measure how long the encryption/decryption takes. startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print('%sion time: %s seconds' % (myMode.title(), totalTime)) # open()函数返回的文件对象 有 write()方法。前提是以'w'或者'a'模式open()的文件对象 # fo = open('filename.txt', 'w') or fo = open('filename.txt', 'a') # write()方法的参数是一个字符串,把这个字符串以相应的方法写入该文件 # Write out the translated message to the output file. outputFileObj = open(outputFilename, 'w') outputFileObj.write(translated) outputFileObj.close() print('Done %sing %s (%s characters).' % (myMode, inputFilename, len(content))) print('%sed file is %s.' % (myMode.title(), outputFilename)) # If transpositionCipherFile.py is run (instead of imported as a module) # call the main() function. if __name__ == '__main__': main()
P.S.
#size参数可选,相应的大小,如果不给那么就读取整个文件内容 size不能过大,小于机器内存的两倍 f.read([size])
#按行读取文件内容,字符串结尾会自动加上一个换行符( \n ),除非最后一行没有以换行符结尾 f.readline()
如果如果 f.readline()
返回一个空字符串,那就表示到达了文件末尾,如果是一个空行,就会描述为 '\n'
#返回一个列表,其中包含了文件中所有的数据行。如果给定了 sizehint 参数,就会读入多于一行的比特数,从中返回多行文本。 f.readlines()
通常用于高效读取大型行文件,避免了将整个文件读入内存。这种操作只返回完整的行。
通过遍历 文件对象de行 来读取文件 每一行-------内存高效、快速,并且代码简洁
>>> for line in fileobj:
... print(line, end='')
...
This is the first line of the file.
Second line of the file
#推荐的文件打开方式
with open("myfile.txt") as f:
for line in f:
print line
文件写入
#将 string 的内容写入文件,并返回写入字符的长度,不是字符串用str()转化成string
f.write(string) 方法
>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
18
关闭文件释放资源
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
用关键字 with 处理文件对象
#优点,自动关闭文件释放资源
>>> with open('/tmp/workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
分类:
Python
, classical crypto-sys
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~