Python - writing and reading from a temporary file

后端 未结 3 2122
离开以前
离开以前 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:30

    In case the file needs to be opened a second time, e.g. read by a different process this might cause trouble on Windows OS:

    Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

    Hence a safe solution is to create a temporary directory instead and then manually create a file therein:

    import os.path
    import tempfile
    
    with tempfile.TemporaryDirectory() as td:
        f_name = os.path.join(td, 'test')
        with open(f_name, 'w') as fh:
            fh.write('')
        # Now the file is written and closed and can be used for reading.
    

提交回复
热议问题