通过读取文本文件创建列表

问题描述 投票:0回答:1

所以,我试图自动完成一项繁琐的任务,我有这样一个test.txt,它总结了一些pdf文件的文件路径。

我有这个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"',
    "",
    "",
]

不知道为什么最后两个对象都是空字符串。

然后,我想创建另一个列表,通过文本行列表循环,并分离路径中的所有内容。

所以,我想要一个包含的列表。

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

最终我希望能够把some_list中的一些索引放到一个新的变量中 这样我就可以在以后创建一个包含这些变量的文件(csv)。

每次我试图循环浏览第一个列表时,我都会得到一个错误信息,告诉我字符串索引超出了范围。

我并不是要求一个完整的脚本,但如果能得到一些关于如何继续使用这个脚本的指导就更好了。

先谢谢你

python text readfile pathname
1个回答
1
投票

也许是这样的?我在这里和那里加了一些有用的评论。

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']

0
投票

你可以尝试使用.split("\")

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

0
投票

首先,你需要清理一下你的输入。那些空字符串可能是文件末尾的空行,所以你必须忽略这些。另外,请注意你的行是用双引号包裹的,这可能不是你想要的。你可以用 .strip('"')

最后,我想 IndexError的原因可能是试图在空行中找到反斜杠,这让我觉得你是在手动搜索它们,而不是使用分割。正如 @Bernd 所说,使用 .split("\\") 的每一行都会将字符串切割成你想要的所有片段,并返回一个包含这些片段的列表。

© www.soinside.com 2019 - 2024. All rights reserved.