美文网首页python百例
91-OOP练习:实现unix2dos和dos2unix功能

91-OOP练习:实现unix2dos和dos2unix功能

作者: 凯茜的老爸 | 来源:发表于2018-08-04 13:38 被阅读0次

windows文本行结束标志是\r\n,非windows的是\n。

import os

class Convert:
    def __init__(self, fname):
        self.fname = fname

    def to_linux(self):
        dst_fname = os.path.splitext(self.fname)[0] + '.linux'
        with open(self.fname, 'r') as src_fobj:
            with open(dst_fname, 'w') as dst_fobj:
                for line in src_fobj:
                    line = line.rstrip() + '\n'
                    dst_fobj.write(line)

    def to_windows(self):
        dst_fname = os.path.splitext(self.fname)[0] + '.windows'
        with open(self.fname, 'r') as src_fobj:
            with open(dst_fname, 'w') as dst_fobj:
                for line in src_fobj:
                    line = line.rstrip() + '\r\n'
                    dst_fobj.write(line)


if __name__ == '__main__':
    c = Convert('/tmp/passwd')  # cp /etc/passwd /tmp
    c.to_linux()
    c.to_windows()

相关文章

网友评论

    本文标题:91-OOP练习:实现unix2dos和dos2unix功能

    本文链接:https://www.haomeiwen.com/subject/dccmvftx.html