在Python中将文件中的新行读写到另一个文件
我正在尝试从一个文件中读取内容,并把这些内容写入另一个文件。问题出现在我想把原文件中的换行符保留到新文件时。
def caesar_encrypt(orig , shift):
enctextCC = open("CCencoded.txt" , 'w')
for i in range(len(orig)):
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) == 10:
enctextCC.write("\n") //doesn't work :(
elif ord(curr) < 97:
enctextCC.write(curr)
elif ord(curr)+shift > 122:
enctextCC.write(chr(ord(curr)+shift-26))
elif ord(curr)+shift >= 97 & ord(curr)+ shift <= 122 :
enctextCC.write(chr(ord(curr)+shift))
enctextCC.close()
有什么建议可以帮我找出问题所在吗?
谢谢
编辑: 解决办法是在外层循环的末尾添加换行符。因为我读取的是一个列表的列表,内层循环基本上就是一行。所以应该像这样:
def caesar_encrypt(orig , shift):
enctextCC = open("CCencoded.txt" , 'w')
for i in range(len(orig)):
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) < 97:
enctextCC.write(curr)
elif ord(curr)+shift > 122:
enctextCC.write(chr(ord(curr)+shift-26))
elif ord(curr)+shift >= 97 & ord(curr)+ shift <= 122 :
enctextCC.write(chr(ord(curr)+shift))
enctextCC.write("\n")
enctextCC.close()
4 个回答
0
当你按行读取一个文件时,其实就是在把文件按行分开,这样会把换行符给丢掉。如果你想保留换行符,可以手动在每行后面加上一个换行符:
enctextCC.write(curr + "\n")
另外一个选择是使用 readline
这个函数来读取第一个文件的行,这样就能保留行末的换行符了。
1
你可以以二进制模式打开文件,这样可以保留换行符:
with open(filenameIn, 'rb') as inFile:
with open(filenameOut, 'wb') as outFile:
for line in inFile:
outFile.write(line)
2
你这样做是不对的
out_file = open("output.txt", "w")
for line in open("input.txt", "r"):
out_file.write(line)
out_file.write("\n")
注意,我们不检查换行符的结尾,因为我们是逐行获取内容的,所以我们可以确定每一行后面都有一个换行符
但是,为什么你需要这样做,而不是直接复制呢?
编辑: 如果你只需要复制一个文件,可以使用这个:
from shutil import copy
copy("input.txt", "output.txt")
如果你需要读取整个文件,可以使用 read()
函数,像这样:
file_data = open("input.txt", "r").read()
# manipulate the data ...
output = open("output.txt", "w")
output.write(file_data)
output.close()
编辑 2: 所以,如果你想把其他 ASCII 值映射到每个字符上,你的做法是对的,但有几点需要注意:
- 你忘记写其他字符了,这样你只会输出
\n
字符 - 确保你真的 读取 了换行符,因为
readlines()
和遍历文件时不会返回换行符。
你的代码应该更像这样:
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) == 10:
enctextCC.write(curr)
else:
enctextCC.write(transformed(curr))