日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python怎么换行继续写脚本_用Python实现换行符转换的脚本的教程

發布時間:2025/4/17 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python怎么换行继续写脚本_用Python实现换行符转换的脚本的教程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

很簡單的一個東西,在'\n'、'\r\n'、'\r'3中換行符之間進行轉換。

用法

代碼如下:

usage: eol_convert.py [-h] [-r] [-m {u,p,w,m,d}] [-k] [-f]

filename [filename ...]

Convert Line Ending

positional arguments:

filename file names

optional arguments:

-h, --help show this help message and exit

-r walk through directory

-m {u,p,w,m,d} mode of the line ending

-k keep output file date

-f force conversion of binary files

源碼

這只能算是argparse模塊和os模塊的utime()、stat()、walk()的一個簡單的練習。可以用,但還相當不完善。

#!/usr/bin/env python

#2009-2011 dbzhang800

import os

import re

import os.path

def convert_line_endings(temp, mode):

if mode in ['u', 'p']: #unix, posix

temp = temp.replace('\r\n', '\n')

temp = temp.replace('\r', '\n')

elif mode == 'm': #mac (before Mac OS 9)

temp = temp.replace('\r\n', '\r')

temp = temp.replace('\n', '\r')

elif mode == 'w': #windows

temp = re.sub("\r(?!\n)|(?

return temp

def convert_file(filename, args):

statinfo = None

with file(filename, 'rb+') as f:

data = f.read()

if '\0' in data and not args.force: #skip binary file... ?

print '%s is a binary file?, skip...' % filename

return

newdata = convert_line_endings(data, args.mode)

if (data != newdata):

statinfo = os.stat(filename) if args.keepdate else None

f.seek(0)

f.write(newdata)

f.truncate()

if statinfo:

os.utime(filename, (statinfo.st_atime, statinfo.st_mtime))

print filename

def walk_dir(d, args):

for root, dirs, files in os.walk(d):

for name in files:

convert_file(os.path.join(root, name), args)

if __name__ == '__main__':

import argparse

import sys

parser = argparse.ArgumentParser(description='Convert Line Ending')

parser.add_argument('filename', nargs='+', help='file names')

parser.add_argument('-r', dest='recursive', action='store_true',

help='walk through directory')

parser.add_argument('-m', dest='mode', default='d', choices='upwmd',

help='mode of the line ending')

parser.add_argument('-k', dest='keepdate', action='store_true',

help='keep output file date')

parser.add_argument('-f', dest='force', action='store_true',

help='force conversion of binary files')

args = parser.parse_args()

if args.mode == 'd':

args.mode = 'w' if sys.platform == 'win32' else 'p'

for filename in args.filename:

if os.path.isdir(filename):

if args.recursive:

walk_dir(filename, args)

else:

print '%s is a directory, skip...' % filename

elif os.path.exists(filename):

convert_file(filename, args)

else:

print '%s does not exist' % filename

時間: 2015-04-15

總結

以上是生活随笔為你收集整理的python怎么换行继续写脚本_用Python实现换行符转换的脚本的教程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。