Pyhton with语句练习 unix文件转换成dos文件
win下面文件格式是
>>> with open('/tmp/unix2dos.txt') as f: ... data = f.read() ... >>> data 'MySQL 5.6 Reference Manual\r\nIncluding MySQL NDB Cluster 7.3-7.4 Reference Guide\r\n\r\nAbstract\r\n\r\nThis is the MySQL? Reference Manual. It documents MySQL 5.6 through 5.6.37, as well as MySQL Cluster releases based on versions 7.3 and 7.4 of NDB through 5.6.36-ndb-7.3.18 and 5.6.36-ndb-7.4.16, respectively.\r\n\r\nMySQL 5.6 features. This manual describes features that are not included in every edition of MySQL 5.6; such features may not be included in the edition of MySQL 5.6 licensed to you. If you have any questions about the features included in your edition of MySQL 5.6, refer to your MySQL 5.6 license agreement or contact your Oracle sales representative.\r\n\r\nFor notes detailing the changes in each release, see the MySQL 5.6 Release Notes.\r\n\r\nFor legal information, see the Legal Notices.\r\n\r\nFor help with using MySQL, please visit either the MySQL Forums or MySQL Mailing Lists, where you can discuss your issues with other MySQL users. '
linux文件格式是
>>> with open('/etc/hosts') as f: ... data = f.read() ... >>> data '127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n::1 localhost localhost.localdomain localhost6 localhost6.localdomain6\n'
可以看到win文件是\r\n结尾的linux文件是\n结尾的
import sys import os def unix2dos(fname): dfname = os.path.splitext(fname)[0] + '.win' with open(fname) as src_fobj: with open(dfname,'w') as dst_fobj: for line in src_fobj: dst_fobj.write(line.rstrip('\n')+ '\r\n') if __name__ == '__main__': try: filename = sys.argv[1] except IndexError: print "usage:%s filename" % sys.argv[0] if not os.path.isfile(filename): print "No such file %s" % filename sys.exit(2) unix2dos(filename) [root@localhost untitled10]# python unix2dos.py /etc/hosts >>> with open('/etc/hosts.win') as f: ... data = f.read() ... >>> data '127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\r\n::1 localhost localhost.localdomain localhost6 localhost6.localdomain6\r\n'