所以我有这个脚本我很满意,虽然它有一个缺陷。更改编码时,它会突然删除文件中的所有数据。不知道为什么。在每行代码中都有注释。
重命名文件 - >移动文件 - >更改编码 - > Exec SQL SP - >移动更改名称+时间戳
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
答案 0 :(得分:2)
codecs.open(.., "w", ..)
打开一个文件进行编写并截断以前的所有内容。它不会为您转换文件。为此,您需要使用其当前编码打开文件,读取其内容,然后使用目标编码以写入模式重新打开它并将内容写回。像
contents = codecs.open(old_filename, "r", encoding="utf-8").read()
codecs.open(new_filename, "w", encoding="utf-16").write(contents)
应该有用。