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

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()

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券