使用python實(shí)現(xiàn)unix2dos和dos2unix命令的例子
由于工作電腦網(wǎng)絡(luò)限制無(wú)法安裝unix2dos和dos2unix命令轉(zhuǎn)換文件,自己實(shí)現(xiàn)一個(gè)
直接上代碼,保存為python文件如unix2dos.py然后使用命令
unix2dos.py {unix2dos|dos2unix} {dirname|filename}
#! /usr/bin/env python # coding=utf-8 import os import sys try: input = raw_input except: pass def usage(): print('Usage:') print('\t %s' % ('unix2dos.py {unix2dos|dos2unix} {dirname|filename}')) def err_exit(msg): if msg: print('%s' % msg) usage() sys.exit(0) def getfiles(root): for dirpath, dirnames, filenames in os.walk(root): for filename in filenames: yield os.path.join(dirpath, filename) def format_file(file, toformat='unix2dos'): print('Formatting %s:\t%s' % (toformat, file)) if not os.path.isfile(file): print('ERROR: %s invalid normal file' % file) return if toformat == 'unix2dos': line_sep = '\r\n' else: line_sep = '\n' with open(file, 'r') as fd: tmpfile = open(file+toformat, 'w+b') for line in fd: line = line.replace('\r', '') line = line.replace('\n', '') tmpfile.write(line+line_sep) tmpfile.close() os.rename(file+toformat, file) def uni_format_proc(filename, toformat): if not toformat or toformat not in ['unix2dos', 'dos2unix']: err_exit('ERROR: %s: Invalid format param' % (toformat)) if not filename or not os.path.exists(filename): err_exit('ERROR: %s: No such file or directory' % (filename)) if os.path.isfile(filename): format_file(filename, toformat) return if os.path.isdir(filename): for file in getfiles(filename): uni_format_proc(file, toformat) if __name__ == '__main__': if len(sys.argv) != 3: err_exit('ERROR: Invalid arguments') uni_format_proc(filename=sys.argv[2], toformat=sys.argv[1])
以上這篇使用python實(shí)現(xiàn)unix2dos和dos2unix命令的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python史上最全種類(lèi)數(shù)據(jù)庫(kù)操作方法分享
本文將詳細(xì)探討如何在Python中連接全種類(lèi)數(shù)據(jù)庫(kù)以及實(shí)現(xiàn)相應(yīng)的CRUD(創(chuàng)建,讀取,更新,刪除)操作,文中的示例代碼講解詳細(xì),需要的可以參考一下2023-07-07Python中tkinter的用戶(hù)登錄管理的實(shí)現(xiàn)
這篇文章主要介紹了Python中tkinter的用戶(hù)登錄管理的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04Python中使用NumPy進(jìn)行數(shù)據(jù)處理方式
這篇文章主要介紹了Python中使用NumPy進(jìn)行數(shù)據(jù)處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02Python3將數(shù)據(jù)保存為txt文件的方法
這篇文章主要介紹了Python3將數(shù)據(jù)保存為txt文件的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09解決mnist數(shù)據(jù)集下載的相關(guān)問(wèn)題
這篇文章主要介紹了解決mnist數(shù)據(jù)集下載的相關(guān)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06