簡體   English   中英

通過讀取文本文件創建列表列表

[英]Create a list of lists from reading a text file

所以我正在嘗試自動化一項繁瑣的任務。

我有這個 test.txt 它總結了一些 pdf 文件的文件路徑。

 "L:\Advertentie woningplattegronden\Definitieve plattegronden\Gemeente Delft\Complex 1004\Copy\1004A0Oa00 Jacob Gillishof 10.pdf"
"L:\Advertentie woningplattegronden\Definitieve plattegronden\Gemeente Delft\Complex 1004\Copy\1004A0Oa00 Jacob Gillishof 11.pdf"
"L:\Advertentie woningplattegronden\Definitieve plattegronden\Gemeente Delft\Complex 1004\Copy\1004A0Oa00 Jacob Gillishof 14.pdf"

我需要我的腳本為第 1 步做的是列出我所做的每一行:

with open('Test.txt') as f:
textlines = f.read().splitlines()
print(textlines)

這導致:

[
    '"L:\\Advertentie woningplattegronden\\Definitieve plattegronden\\Gemeente Delft\\Complex 1004\\Copy\\1004A0Oa00 Jacob Gillishof 10.pdf"',
    '"L:\\Advertentie woningplattegronden\\Definitieve plattegronden\\Gemeente Delft\\Complex 1004\\Copy\\1004A0Oa00 Jacob Gillishof 11.pdf"',
    '"L:\\Advertentie woningplattegronden\\Definitieve plattegronden\\Gemeente Delft\\Complex 1004\\Copy\\1004A0Oa00 Jacob Gillishof 14.pdf"',
    "",
    "",
]

不知道為什么最后兩個對象是空字符串。

然后我想創建另一個列表,該列表循環遍歷 textlines 列表並分隔路徑 \ 中的所有內容

所以我想要一個包含以下內容的列表:

some_list = [
    "L:",
    "Advertentie woningplattegronden",
    "Definitieve plattegronden",
    "Gemeente Delft",
    "Complex 1004",
    "Copy",
    "1004A0Oa00 Jacob Gillishof 10.pdf",
]

最終,我希望能夠將 some_list 中的一些索引放入一個新變量中,以便稍后創建一個包含這些變量的文件 (csv)。

每次我嘗試遍歷第一個列表時,都會收到一條錯誤消息,告訴我字符串索引超出范圍。

順便說一句,我並不是要一個完整的腳本,但是關於如何繼續使用這個腳本的一些指導會很好。

提前致謝!

像這樣的東西,也許? 我在這里和那里發表了一些有用的評論。

filenames = []

with open("file.txt", "r") as file:
    for line in file:
        line = line.strip()  # remove any trailing/leading spaces
        line = line.strip('"')  # remove wrapping quotes
        if line:  # if there still is content...
            filenames.append(line)  # save the valid line.

filename_components = [
    filename.split("\\")  # Split the filename by backslashes
    for filename in filenames  # for each filename  # in the filenames we just stored
]

for split_name in filename_components:
    print(split_name)  # print out each split name

輸出例如

['L:', 'Advertentie woningplattegronden', 'Definitieve plattegronden', 'Gemeente Delft', 'Complex 1004', 'Copy', '1004A0Oa00 Jacob Gillishof 10.pdf']
['L:', 'Advertentie woningplattegronden', 'Definitieve plattegronden', 'Gemeente Delft', 'Complex 1004', 'Copy', '1004A0Oa00 Jacob Gillishof 11.pdf']
['L:', 'Advertentie woningplattegronden', 'Definitieve plattegronden', 'Gemeente Delft', 'Complex 1004', 'Copy', '1004A0Oa00 Jacob Gillishof 14.pdf']

您可以嘗試使用.split("\")

splittedLines = [l.split("\") for l in textlines]

首先,您需要稍微清理一下您的輸入。 這些空字符串可能是文件末尾的空行,因此您必須忽略它們。 另外,請注意您的行用雙引號括起來,這可能不是您想要的。 您可以使用.strip('"')刪除它們

最后,我猜IndexError可能來自試圖在空行中找到反斜杠,這讓我覺得你是手動搜索它們而不是使用拆分。 正如@Bernd 所說,在每一行上使用.split("\\")會將字符串切割成您想要的所有部分並返回一個列表。

暫無
暫無

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

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