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