1、場景javascript
工做須要,有時要將文件上傳到 unix 的服務器,但願將文件的格式改成 Unix(LF), 能夠經過py腳原本批量處理。java
2、代碼服務器
import os # 轉換文件格式和編碼方式 def to_lf(path, isLF, encoding = 'utf-8'): """ :param path: 文件路徑 :param isLF: True 轉爲Unix(LF) False 轉爲Windows(CRLF) :param encoding: 編碼方式,默認utf-8 :return: """ newline = '\n' if isLF else '\r\n' tp = 'Unix(LF)' if isLF else 'Windows(CRLF)' with open(path, newline=None, encoding=encoding) as infile: str = infile.readlines() with open(path, 'w', newline=newline, encoding=encoding) as outfile: outfile.writelines(str) print("文件轉換成功,格式:{0} ;編碼:{1} ;路徑:{2}".format(tp, encoding, path)) if __name__ == "__main__": rootdir = r'C:\Users\Administrator\Desktop\testl' isLF = True # True 轉爲Unix(LF) False 轉爲Windows(CRLF) path_list = os.listdir(rootdir) #path_list.sort(key=lambda x:int(x[:-4])) #對讀取的路徑進行排序 for filename in path_list: path = os.path.join(rootdir,filename) to_lf(path, isLF)