Python: os.walk() placing files in unexpected locations

时间:2018-07-25 04:42:22

标签: os.walk chemistry

I have code that intends to iterate through a directory hierarchy, and, for every file at the bottom of the hierarchy, create a file.

for currentDirectory, listOfSubDirectories, listOfStructures in os.walk(projectsLocation):

#this says if we arent at the bottom of the directory chain, do nothing (checks if subDirectoryList is 0)
    if not listOfSubDirectories:

        ##THIS IS WHERE WE DO THINGS FOR ONE SIMULATION##
        for currentStructure in listOfStructures:

            if "Abridged" in currentStructure:
                os.remove(currentStructure)


            abridgedVersion=open(currentStructure[:-4]+"Abridged","w+")

Extremely bizarrely, however, is that the code places 2 of the files files at the top of the directory!

Even stranger is that when i rerun the code with error-checking print statements, printing the three lists, the files that get printed at the top of the directory "cant be found" despite the fact that they arent even in the list of files!

i.e.

/home/parker/pretendFoldingData/proj8202/run2/clone1
[]
['structure1.pdb', 'structure0Abridged', 'structure0.pdb']
Traceback (most recent call last):
  File "importAtomFileMaker.py", line 35, in <module>
    os.remove(currentStructure)
FileNotFoundError: [Errno 2] No such file or directory: 'structure1Abridged'

I hope this was even slightly clear..... can someone please advise?

1 个答案:

答案 0 :(得分:0)

来自朋友:

您的代码中有错误; 至少2。 尤其是当您尝试重命名文件时。

    除非给出绝对路径,否则
  1. open(“ path”,'w +')将创建一个与当前工作目录相关的文件。通过执行此操作来解决此问题 base_path = os.path.join(currentDirectory, structure) 然后 open(base_path + <filename>, 'w+') ... 这将确保您创建的文件将相对于当前目录放置。
  2. 代替重命名文件而不是删除文件,而是创建一个空白文件 如果不是listOfDirectories,也有点“ hacky”。 我认为最好将当前目录重新注册为您期望为真的模式