更改python编码时数据从文件中消失
所以我对这个脚本非常满意,尽管它有一个缺陷。更改编码时,它会突然从文件中删除所有数据。不知道为什么。在代码中为每一行的功能添加注释 重命名文件-->移动文件-->更改编码-->执行SQL SP-->移回更改名称+时间戳更改python编码时数据从文件中消失,python,python-2.7,encoding,Python,Python 2.7,Encoding,所以我对这个脚本非常满意,尽管它有一个缺陷。更改编码时,它会突然从文件中删除所有数据。不知道为什么。在代码中为每一行的功能添加注释 重命名文件-->移动文件-->更改编码-->执行SQL SP-->移回更改名称+时间戳 import os import shutil import glob import pyodbc import os.path import datetime import codecs #Defining function for SP def SP(): cnxn =
import os
import shutil
import glob
import pyodbc
import os.path
import datetime
import codecs
#Defining function for SP
def SP():
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=serv400;DATABASE=db;Trusted_Connection=yes')
cursor = cnxn.cursor()
query = "exec [PD_ABC_SP]"
cursor.execute(query)
cnxn.commit()
#Changing name, moving, importing and changing encoding for files in loop
destdir = '\\\\serv400\\f$\\BulkInsert\\Steve\\'
srcdir = '\\\\sesrv414\\Applications\\Prod\\IMP\\Phone\\'
inldir = '\\\\sesrv414\\Applications\\Prod\\IMP\\Phone\\Inlasta\\'
newfilename = 'Phone_Import_ABC.csv'
now = datetime.datetime.now() #Adding datetime for timestamp
for oldfilename in os.listdir(srcdir): #Looping through files in directory
if oldfilename.endswith(".csv"): #Changes filenames on files where name ends with csv
os.rename(srcdir + oldfilename, destdir + newfilename) #Changing old path + filename
codecs.open(destdir + newfilename, "w", encoding="utf-16") #switch encoding
SP() #Executing the function for the stored procedure
os.rename(destdir + newfilename, inldir + oldfilename + now.strftime("%Y%m%d"))
#Moving back the files including the timestamp
codecs.open(..,,..)
打开一个文件进行写入并截断以前的任何内容。它不会为您转换文件。为此,您需要使用当前编码打开文件,读取其内容,然后使用目标编码以写模式重新打开文件,然后将内容写回。差不多
contents = codecs.open(old_filename, "r", encoding="utf-8").read()
codecs.open(new_filename, "w", encoding="utf-16").write(contents)
应该可以工作。执行
编解码器时,文件会被截断。打开(…,“w”)
。您试图实现的是什么?在通过存储过程将文件导入SQL之前,我正在尝试更改文件的编码,因为在名称中有一些瑞典字母åäö,由于MS SQL server的原因,在UTF-8中无法正确匹配2008@Phillip忘记在上一条评论中标记您:)