激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - Python批量轉換文件編碼格式

Python批量轉換文件編碼格式

2020-06-30 09:42Python教程網 Python

需要將工作目錄下的文件進行轉碼,開始的編碼是GBK的,需要將其轉換為utf-8的。文件較多,手動轉換肯定不行,用Python寫個腳本來實現。

自己寫的方法,適用于linux,

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/python
#coding=utf-8
import sys
import os, os.path
import dircache
import commands
def add(x,y):
 return x*y
 
def trans(dirname):
 lis = dircache.opendir(dirname)
 for a in lis:
af=dirname+os.sep+a
## print af
 if os.path.isdir(af):
## print af
trans(af)
else:
 ## print af+"encoding="+fi.name
 ft = commands.getoutput('file -i '+af)
## print ft
 if a.find('.htm')==-1 and a.find('.xml')==-1 and ft.find('text/')!=-1 and ft.find('iso-8859')!=-1:
 print 'gbk'+ft+">"+af
 commands.getoutput('iconv -ficonv -f gbk -t utf-8 -c -o'+""+af+""+af)
 
trans(os.getcwd())

py2.6以下版本可用代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import os,sys
 
def convert( filename, in_enc = "GBK", out_enc="UTF8" ):
  try:
    print "convert " + filename,
    content = open(filename).read()
    new_content = content.decode(in_enc).encode(out_enc)
    open(filename, 'w').write(new_content)
    print " done"
  except:
    print " error"
 
def explore(dir):
  for root, dirs, files in os.walk(dir):
    for file in files:
      path = os.path.join(root, file)
      convert(path)
 
def main():
  for path in sys.argv[1:]:
    if os.path.isfile(path):
      convert(path)
    elif os.path.isdir(path):
      explore(path)
 
if __name__ == "__main__":
  main()

支持py3.1的版本

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import os
import sys
import codecs
#該程序用于將目錄下的文件從指定格式轉換到指定格式,默認的是GBK轉到utf-8
def convert(file,in_enc="GBK",out_enc="UTF-8"):
try:
print ("convert " +file)
f=codecs.open(file,'r',in_enc)
new_content=f.read()
codecs.open(file,'w',out_enc).write(new_content)
#print (f.read())
except IOError as err:
print ("I/O error: {0}".format(err))
 
 
def explore(dir):
for root,dirs,files in os.walk(dir):
for file in files:
path=os.path.join(root,file)
convert(path)
 
def main():
for path in sys.argv[1:]:
if(os.path.isfile(path)):
convert(path)
elif os.path.isdir(path):
explore(path)
 
if __name__=="__main__":
main()

以上所述就是本文 的全部內容了,希望大家能夠喜歡。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲网站一区 | 免费a视频| 国产精品久久久久久久久久大牛 | 免费人成年短视频在线观看网站 | 91短视频在线观看视频 | 欧美在线黄色 | 亚州综合网| 成人福利电影在线观看 | 中文字幕国产日韩 | 免费看欧美一级特黄a大片 久久免费视频一区二区三区 | 精品国产一区二区三区在线 | 欧美日本色| 亚洲欧美日韩在线 | 国产精品探花在线观看 | 久久精品人人做人人爽 | 久久久久久免费免费 | 欧美日韩在线播放 | 亚洲成人久久精品 | 亚洲情视频 | 天天操天天操天天操天天操天天操天天操 | 久久精品首页 | 亚洲一区久久久 | 久久精品免费国产 | 99精品电影 | 大尺度福利视频 | 精品亚洲一区二区 | 午夜啪视频 | h视频免费观看 | 2019亚洲日韩新视频 | 日韩一级视频 | 好吊色37pao在线观看 | 午夜精品区 | 毛片在线免费 | 国产午夜精品理论片a级探花 | 鲁丝片一区二区三区免费入口 | 国产在线看一区 | 午夜热门福利 | 国产xxxx岁13xxxxhd | 国产九色在线观看 | 国产免费www | 日韩精品中文字幕一区二区三区 |