Python - writing and reading from a temporary file

后端 未结 3 2126
离开以前
离开以前 2021-02-06 22:51

I am trying to create a temporary file that I write in some lines from another file and then make some objects from the data. I am not sure how to find and open the temp file s

3条回答
  •  渐次进展
    2021-02-06 23:07

    As per the docs, the file is deleted when the TemporaryFile is closed and that happens when you exit the with clause. So... don't exit the with clause. Rewind the file and do your work in the with.

    with tempfile.TemporaryFile() as tmp:
        lines = open(file1).readlines()
        tmp.writelines(lines[2:-1])
        tmp.seek(0)
    
        for line in tmp:
            groupId = textwrap.dedent(line.split(':')[0])
            artifactId = line.split(':')[1]
            version = line.split(':')[3]
            scope = str.strip(line.split(':')[4])
            dependencyObject = depenObj(groupId, artifactId, version, scope)
            dependencyList.append(dependencyObject)
    

提交回复
热议问题