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

标签 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 = 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)

应该可以。

关于python - 更改编码python时数据从文件中消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27174498/

相关文章:

python - 如何导出张量板数据?

python - 如何将文本小部件内容设置为 Python/Tkinter 中的变量值?

python-2.7 - 我如何从本应在命令行上运行的脚本调用Python函数

python - 限制 tk 小部件上的条目

python - "not in"比较未按预期工作

Python 3 - 将字符串转换为数字

python - Jupyter 卡在 pip install 中

Python mysqlclient和数据在两个不同的服务器上

video - 使用 ffmpeg 将静止图像编码为 mpeg-2 视频时如何避免泵送伪影

php - 通过 PHP 将 ♥ 插入 MySQL(心形)