Skip to main content
 首页 » 编程设计

python之更改编码python时数据从文件中消失

2024年10月25日10sxdcgaq8080

所以我得到了这个我非常满意的脚本,尽管它有一个缺陷。更改编码时,它会突然从文件中删除所有数据。不知道为什么。在代码中对每一行的作用进行评论。

重命名文件 --> 移动文件 --> 更改编码 --> 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 

请您参考如下方法:

codecs.open(.., "w", ..) 打开一个文件进行写入并截断任何以前的内容。它不会为您转换文件。为此,您需要使用其当前编码打开文件,读取其内容,然后使用目标编码以写入模式重新打开它并将内容写回。有点像

contents = codecs.open(old_filename, "r", encoding="utf-8").read() 
codecs.open(new_filename, "w", encoding="utf-16").write(contents) 

应该可以。