首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >91-OOP练习:实现unix2dos和dos2unix功能

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

作者头像
凯茜的老爸
发布于 2018-09-11 15:03:05
发布于 2018-09-11 15:03:05
7310
举报
文章被收录于专栏:python百例python百例

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

代码语言:javascript
复制
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()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.08.04 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档