簡體   English   中英

在字符和符號之間獲取字符串,而不關心符號后面的內容

[英]Getting string between a character and a symbol, without caring about what follows the symbol

為了將一些文件排序到文件夾中,我必須獲取兩個文件夾的編號(好像是某種 ID)(命名為 pX,p.fixed,X 是一個范圍從 1 到 200150 的數字)和文件(為PX_N.gmspr,其中P為固定值,X為文件夾ID號,N為文件標識,可以是2、3、6、8、9、A、H)。

例如 p.24 和 P24_2.gmspr、P24_3.gmspr、P24_6.gmspr、P24_8.gmspr、P24_9.gmspr、P24_A.gmspr 和 P24_H.gmspr,以便將所有 P24_N.gmspr 移動到 p.24

PX_N.gmspr 文件與目標文件夾 pX 位於不同的文件夾中。 一點 os.chdir 和 os.rename 和文件可以很容易地移動,所以我相信這不是問題。

我想要的是獲取文件名的 X 編號以與文件夾編號進行比較,忘記 P 和 _N.gmspr 字符串。 雖然我可以通過foldername.split(".",1)[1]獲取文件夾編號,但我真的不知道如何為文件編號做這件事。

綜上所述,我想將一些名為 PX_N.gmspr 的文件移動到另一個文件夾,該文件夾標識幾乎相同的 pX

任何想法? 謝謝!!!

編輯:關於給出的答案,我必須澄清自己要做什么,特別是文件和文件夾格式:

Mother folder
├── Unclassified
│   └── All PX_N.gmspr being PX certain files that gotta be moved to another folders, X a number that ranges from 1 to 200150 (but not exactly 200150, is just a number ID) and N can be only 2, 3, 6, 9, A or H, nothing more. In total 15435 elements with each of the X having one of the 6 possibles N gmspr.
├──First Folder
│   └── p.X folders (X from 1 to 151), the aim is to select all the PX_N.gmspr files that agree with the X number that matches the p.X of the folder and move it to each folder.
├──Second Folder
│   └── p.X folders (X from 152 to 251, plus p.602 to p.628, p.823, p.824, 
│         p.825, p.881 and p.882)
└──Third Folder
    └── p.X folders (X from 252 to 386, plus p.585, p.586 and p. 587) 

還有一些其他文件夾可以訂購更多的 15435 文件。 我目前正在搜索正則表達式; 對我來說不幸的是,這是我第一次真正必須使用它們。

編輯原因已解決:所以重點是使用正則表達式並僅獲取數字,但隨后出現嵌套列表,只有第一個數字有用

這是正則表達式的完美工作。

首先,讓我們創建一個臨時目錄並在其中填充一些文件以進行演示。

from pathlib import Path
from random import choices, randint
from string import ascii_letters

from tempfile import TemporaryDirectory

tmpdir = TemporaryDirectory()

for i in range(4):
    n = randint(1, 999)
    for i in range(randint(1, 5)):
        Path(
            tmpdir.name, f"P{n}.{''.join(choices(ascii_letters, k=10))}"
        ).touch()

現在我們有 4 種類型的文件 (PN.),這種類型有 1 到 5 個文件。

然后,我們只需要遍歷這些文件,使用正則表達式P(\d+)\..+從文件名中提取 N,最后創建目標目錄並移動文件。

from pathlib import Path
import re

dir_re = re.compile(r"P(\d+)\..+")

for filepath in Path(tmpdir.name).iterdir():
    m = dir_re.match(filepath.name)
    dirpath = filepath.parent / f"p.{m.group(1)}"
    if not dirpath.is_dir():
        dirpath.mkdir()
    filepath.rename(dirpath / filepath.name)

例如,從一個平面臨時目錄中,我們現在對以下內容進行了排序。

/var/folders/lf/z7ftpkws0vn7svq8n212czm40000gn/T/tmppve5_m1u/
├── p.413
│   └── P413.yJvxPtuzfz
├── p.705
│   ├── P705.DbwPyiFxum
│   ├── P705.FVwMuSqFms
│   ├── P705.PZyGIQEqSG
│   ├── P705.baRrkcNaZR
│   └── P705.tZKFTKwDah
├── p.794
│   ├── P794.CQTBgXOckQ
│   ├── P794.JNoKsUtgRU
│   └── P794.iSdrdohKYq
└── p.894
    └── P894.XbzFxnqYOY

最后,清理臨時目錄。

tmpdir.cleanup()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM