使用Python将日文字符输出到文件 [英] Outputting Japanese Characters to a File using Python

查看:442
本文介绍了使用Python将日文字符输出到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标->我正在尝试使用 Python

Goal --> I am trying to automate the query execution process using Python

详细信息->我的源是 Teradata 数据库,目标是 .txt 文件

Detail --> My Source is Teradata Database and Destination is .txt file

我正在编写Python代码以在Teradata中运行查询并将输出保存为.txt文件.

I am writing a Python code to run a query in Teradata and save the output in .txt file.

问题->即使可以运行查询并保存输出,日语字符也显示为"\ x1a \ x1a"

Issue --> Even though,I am able to run the query and save the output,The Japanese Character are showing up as "\x1a\x1a"

对于ex.当我运行查询时,我在Teradata SQL Assistant窗口中看到的输出是爱してる",而文本文件中的输出是"\ x1a \ x1a"
我正在使用"PYCharm"进行编码
我正在使用下面的代码编写文件

For ex . when i run the query the output i see in Teradata SQL Assistant window is "愛してる"  while the output in text file is "\x1a\x1a"
I am using "PYCharm" for coding
I am using below code for writing the file

#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
import io  
import pyodbc  
import os  

#Establish connection with Teradata  
conn = pyodbc.connect('Coneection Parameters')  
conn.setencoding(encoding='utf-8')  
cur = conn.cursor()  
conn.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')

#Reading Query  
scriptFile = open('query.sql','r')  
script = scriptFile.read()  
scriptFile.close()  

#Executing Query  
cur.execute(script)  
rows = cur.fetchall()  

#Writing the output to file  
with open('results.txt','w') as f:  
   print(rows)  
   f.write('%s\n' % rows)  

#Closing the Connection  
cur.close()#close the query writing  
conn.close() 

使用的变量
results.txt ->目标文件,我要在其中写入日语​​字符

The variables used
results.txt -> Target File,where i want to write the Japanese Character

样品输出我期望ペット用品

我在文件"results.txt"中获得的输出-> [('\ x1a \ x1a \ x1a \ x1a \ x1a',)]

The Output I am getting in File "results.txt" --> [('\x1a\x1a\x1a\x1a\x1a', )]

推荐答案

让我们解决标题问题.要将日语(或任何语言)输出到文件,请执行以下操作:

Let's solve the title problem. To output Japanese (or any language) to a file:

  1. 以Unicode字符串开头.
  2. 打开文件进行写入并指定编码.
  3. 将字符串写入文件.

使用Python 3的示例:

Example using Python 3:

s = 'ペット用品'
with open('results.txt','w',encoding='utf8') as f:
    f.write(s)

您的rows不是Unicode字符串,而是一个包含不正确字符串的元组的列表.那是您必须解决的另一个问题.

Your rows isn't a Unicode string, but a list with a tuple with an incorrect string. That's another problem you'll have to solve.

这篇关于使用Python将日文字符输出到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆