python 读取指定文件信息并拼接

python 读取指定文本并拼接成指定的格式

# -*- coding: utf-8 -*-
import os

def getHelloWorld(path, fileName):
    """
    :param path:
    :param fileName:
    :return: string
    """
    try:
        os.path.isdir(path)
    except Exception as e:
        raise e
    else:
        resHello = ''
        resWorld = ''
        absPath = os.path.abspath(path)
        if absPath.endswith("\\"):
            filePath = absPath.replace('\\','\\\\') + fileName
            if os.path.isfile(filePath):
                with open(filePath)as f:
                    txt = f.readlines()
                resHello = txt[0].split('_')[0]
                resWorld = txt[1].split(' ')[0]
            return resHello + resWorld
        else:
            filePath = (absPath + ' ').replace(' ','\\\\') + fileName
            if os.path.isfile(filePath):
                with open(filePath)as f:
                    txt = f.readlines()
                resHello = txt[0].split('_')[0]
                resWorld = txt[1].split(' ')[0]
            return resHello + resWorld


def getHelloAndChina(path, fileName):
    """
    :param path:
    :param fileName:
    :return: string
    """
    try:
        os.path.isdir(path)
    except Exception as e:
        raise e
    else:
        resHello = ''
        resWorld = ''
        absPath = os.path.abspath(path)
        if absPath.endswith("\\"):
            filePath = absPath.replace('\\', '\\\\') + fileName
            if os.path.isfile(filePath):
                with open(filePath)as f:
                    txt = f.readlines()
                resHello = txt[0].split('_')[0]
                resWorld = txt[1].split(' ')[1].split('_')[0]
            return resHello + resWorld
        else:
            filePath = (absPath + ' ').replace(' ', '\\\\') + fileName
            if os.path.isfile(filePath):
                with open(filePath)as f:
                    txt = f.readlines()
                resHello = txt[0].split('_')[0]
                resWorld = txt[1].split(' ')[1].split('_')[1]
            return resHello + resWorld

if __name__ == '__main__':
    print getHelloWorld('.', 'test.txt')
    print getHelloAndChina('.', 'test.txt')

文本内容如下:

Hello_123
World 456_China
posted @ 2019-05-01 13:40  代码诠释的世界  阅读(834)  评论(0编辑  收藏  举报