python 操作 文件 demo

其他技术

2017-12-27

39

0

技术:python2.7

运行环境:win7

demo功能:提供一个python处理文件的demo

操作步骤

1. 填充要处理的文件data.txt, 需要utf-8编码

2. 运行app.py

3. 可以看到控制台输出 转化后的结果。具体看效果图

读取文件、处理代码

#单个文件输出
def change_file(file_path):
    if not os.path.isdir(file_path) and not os.path.isfile(file_path):
        print "file not found"
        return
    file_pointer = open(file_path)
    line = file_pointer.readline()
    while line:
        line = line.replace("\n","")
        output_file_content(line)
        line = file_pointer.readline()

    file_pointer.close()

列出一个目录中的文件并处理

#多个文件保存
def change_dir_sources(dir):
    if not os.path.isdir(dir):
        print "dir not found"

    out_dir = dir + 'data'
    is_exits = os.path.exists(out_dir)
    if not is_exits:
        os.makedirs(out_dir) 


    list = os.listdir(dir)#列出目录下的所有文件和目录
    for line in list:
        if line.find('.java') < 0:
            continue

        result = ''
        filepath = os.path.join(dir, line)
        result = get_change_file(filepath)
        out=file(get_new_file_full_name(filepath) ,"w")
        out.write(result)
        out.close()

    print 'finished'

字符串包含子串、替换、正则匹配

def get_file_content(line):
    result = ''
    if line.find("public class") >= 0:
        result = result + line.replace("implements","").replace("SpecificRecord","") + "{\n"
        return result

    if line.find("@FieldDoc") >= 0:
        line = line.replace('(\"', '|').replace('\")','|')
        array = line.split('|')
        result = result + "/** \n"
        result = result + "* " + array[1] + "\n"
        result = result + "*/" + "\n"
        return result
    if line.find("@JsonProperty") >= 0:
        result = result + line +"\n"
        return result

    group = field_pattern.match(line)
    if group:
        result = result + group.string + "\n"
        result += build_get_set(group.string)
        return result

    return result

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think