【问题标题】:some dotfiles aren't removed in array of files after deleting entries that start with "."删除以“。”开头的条目后,某些点文件不会在文件数组中删除。
【发布时间】:2018-10-29 03:30:15
【问题描述】:

由于某些原因,有些文件以“.”开头。在第二个print() 调用中,即使它们应该在for 循环中被删除

from os import *

cwd = getcwd()                                                                                                                               
cfiles = listdir(cwd)

print(str(cfiles) + "\n")

for files in cfiles:
    if files[0] == ".":
        cfiles.pop(cfiles.index(files))
    else:
        continue

print(cfiles)

【问题讨论】:

  • 也许他们在点之前有空格。

标签: python python-3.x file io


【解决方案1】:

您不应删除for 循环内的列表元素。尝试类似:

from os import *

cwd = getcwd()                                                                                                                               
cfiles = listdir(cwd)

print(str(cfiles) + "\n")
index = 0
while index < len(cfiles):
    files = cfiles[index]
    if files[0] == ".":
        cfiles.pop(cfiles.index(files))
    else:
        index += 1

print(cfiles)

【讨论】:

  • 但是在调试时,当在“for .. in”循环中时,项目被删除并且列表末尾有更新的值。我想这是可能的,因为列表是可变的,对吧?
  • 使用for 循环的问题在于它使用了在循环开始时创建的迭代器。如果循环的元素被删除,迭代器可能会丢失。
  • 是的!说得通。当元素被移到左边时,索引会混淆,因为一个项目被删除。谢谢约翰
【解决方案2】:

试试这个版本。效果很好:

from os import *

cwd = getcwd()
cfiles = list()
for file in listdir(cwd):
    if file[0] == ".":
        continue
    else:
        cfiles.append(file)

print(cfiles)

但是很奇怪,当 'for.. in' 与 cfiles 一起使用时,列表 cfiles 中的一些文件(在我的情况下是调试时的 .gitignore 和 config.yml)被忽略了。

希望解决方案有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2019-12-15
    • 1970-01-01
    • 2014-02-19
    • 2014-12-13
    • 1970-01-01
    相关资源
    最近更新 更多