Python 将输出数据保存到文本文件中(每行单独一行)

Python 将输出数据保存到文本文件中(每行单独一行),python,Python,我想将输出数据保存到文本文件中,在该文件中,每一新行显示在不同的行中。当前,每行都由分隔符分隔\n,我希望新行保存在不同的行中 from PIL import Image import pytesseract import sys from pdf2image import convert_from_path import os PDF_file = "F:/ABC/Doc_1.pdf" pages = convert_from_path(PDF_file, 500) ima

我想将输出数据保存到文本文件中,在该文件中,每一新行显示在不同的行中。当前,每行都由分隔符分隔\n,我希望新行保存在不同的行中

from PIL import Image 
import pytesseract 
import sys 
from pdf2image import convert_from_path 
import os 



PDF_file = "F:/ABC/Doc_1.pdf"

pages = convert_from_path(PDF_file, 500) 
image_counter = 1

for page in pages: 
    filename = "page_"+str(image_counter)+".jpg"
    page.save(filename, 'JPEG') 
    image_counter = image_counter + 1

filelimit = image_counter-1
outfile = "F:/ABC/intermediate_steps/out_text.txt"


f = open(outfile, "a") 

for i in range(1, 2): 

    filename = "page_"+str(i)+".jpg"
    import pytesseract 
    pytesseract.pytesseract.tesseract_cmd = r"\ABC\opencv-text-detection\Tesseract-OCR\tesseract.exe"
    from pytesseract import pytesseract
    text = str(((pytesseract.image_to_string(Image.open(filename)))))  
    text = text.replace('-\n', '')   
    #text = text.splitlines()
    f.writelines("Data Extracted from next page starts now.")
    f.writelines(str(text.encode('utf-8')))

f.close() 
例如:

ABC
DEF
GHI
电流输出:-

ABC\nDEF\nGHI\n
当你这样做的时候

f.writelines(str(text.encode('utf-8')))
将换行符字节\n转换为其转义版本\\n。你应该使用

f.writelines(text)

我不明白你的问题。有什么问题?@m02ph3u5,我希望将提取的输出保存在一个文本文件中,其中每一新行不显示为以\n分隔,但每一新行都保存在不同的行中,没有\n,请参阅我在问题中包含了一个图像。我希望能有所帮助。
文本的确切内容是什么?另外,如果只是一个字符串,为什么要使用
writelines
而不是
write
?它是从一个pdf文档中提取的数据@m02ph3u5@m02ph3u5写一行又一行,它们都不适用于我。如果我不编码,则会抛出一个错误:UnicodeEncodeError:“charmap”编解码器无法对位置0中的字符“\ufb01”进行编码:字符映射到您可以尝试