利用Python做工具-3

本文介绍了一种Python工具,用于比较两个目录中相同文件名的文件,并将这些文件的第一行格式化输出到一个新文件中。此工具适用于需要从不同源收集数据并统一格式的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里只针对工作中用的问题而写的Python工具做个记录,以便以后查阅,无他,没优化,只是实现功能:

问题描述:

取两个目录中的相同文件名的文件并各自取出第一行格式化并输出到一个文件。

需求解析:

第一个目录为主,第二个目录为辅,在第一个目录中找到一个文件后取出第一行,再在第二个目录中找到该文件,进行同样的操作,为了通用,依然使用配置config.ini。

解决方案:

配置config.ini如下:


代码如下:

 Python Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# -*- coding:  utf-8 -*-
#!/usr/bin/python
# filename: comparetools.py
# codedtime:2015-5-18

import os
import configparser

# 遍历一个目录,输出所有文件名
def itemsbrowse(path):
    for home, dirs, files in os.walk(path):
        for filename in files:
            yield os.path.join(home, filename)

# 获得格式的标题行   
def getformatedTitle(fullname):
    file = open(fullname, 'r')
    strline = file.readline()
    strline = strline.replace('\t''|')
    file.close()
    
    return strline
    

# 添加到指定的文件
def addtofile(fullname, strline):
    file = open(fullname, 'a')      
    file.write(strline)
    file.close()

def excute():
    iniconf = configparser.ConfigParser()
    iniconf.read('config.ini')
    ifilepath   = iniconf.get('setting''ifilepath')
    ifilepath2  = iniconf.get('setting''ifilepath2')
    ofile       = iniconf.get('setting''ofile')

    if os.path.exists(ofile):
        os.remove(ofile)
    
    for fullname in itemsbrowse(ifilepath):
        try:
            filename    = os.path.basename(fullname) # 文件名
            fullname2   = ifilepath2 + "\\" + filename

            printchars = filename + '\n'
            printchars += getformatedTitle(fullname)
            
            if os.path.exists(fullname2):
                printchars += getformatedTitle(fullname2)
                
            addtofile(ofile, printchars + '\n')
            
        except Exception as err:
            print(err)
            continue
        
            
if __name__ == '__main__':
    excute()
输出结果:

这里第二目录为空, 输出如下:


心得体会:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值