Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从文本文件中的行分割内容_Python_Partitioning - Fatal编程技术网

Python 从文本文件中的行分割内容

Python 从文本文件中的行分割内容,python,partitioning,Python,Partitioning,我在一个文本文件中有一些数据,主要是文件夹的路径 home/user/Desktop/arandomname/2017/01 home/user/Desktop/couldbeanothername/2017/01 home/user/Desktop/guesswhatname/2017/01 我想选择Desktop/和/2017之间的字符串,我尝试使用position,但肯定不起作用,因为字符串长度不同 目前我正在使用 for i in content: print i.partit

我在一个文本文件中有一些数据,主要是文件夹的路径

home/user/Desktop/arandomname/2017/01
home/user/Desktop/couldbeanothername/2017/01
home/user/Desktop/guesswhatname/2017/01
我想选择Desktop/和/2017之间的字符串,我尝试使用position,但肯定不起作用,因为字符串长度不同

目前我正在使用

for i in content:
    print i.partition('/')[-1].rpartition('/20')[0]
产量高达

home/user/Desktop/arandomname
home/user/Desktop/couldbeanothername
home/user/Desktop/guesswhatname
有什么建议吗?

使用re模块

使用拆分

needed_data = content.split("/")[3]

您可以使用正则表达式:

s = 'home/user/Desktop/arandomname/2017/01'
re.findall("Desktop/([^/]+)/\d{4}", s)[0]
# 'arandomname'
或直接搜索:

m = s[s.index('Desktop/') + len('Desktop/') : ]
m[ : m.index('/')]
# 'arandomname'
您可以使用:

返回组成路径的目录和文件的元组


该模块提供了更多与路径相关的方法,以备您需要。

显然不是OP所要求的。在进行向下投票之前,请检查有问题的编辑。@gilgameshbk欢迎您!那么请接受并投票?答案是。谢谢。说我的名声不到15,不会显示,对不起,你能标记正确答案吗?
m = s[s.index('Desktop/') + len('Desktop/') : ]
m[ : m.index('/')]
# 'arandomname'
from pathlib import Path

content = [
    'home/user/Desktop/arandomname/2017/01',
    'home/user/Desktop/couldbeanothername/2017/01',
    'home/user/Desktop/guesswhatname/2017/01']

for strg in content:
    path = Path(strg)
    print(path.parts[3])

# prints:
# arandomname
# couldbeanothername
# guesswhatnam