Kev*_*uan 6 python linux windows io file-io
我有以下代码:
import os
import sys
import tempfile
import subprocess
with tempfile.NamedTemporaryFile('w+') as f:
if sys.platform == 'linux':
subprocess.call('vim', f.name)
elif sys.platform == 'nt':
os.system(f.name)
Run Code Online (Sandbox Code Playgroud)
它foobar.txt可以vim在Linux上使用,也可以在Windows上使用默认编辑器打开.在Linux上它工作正常:tempfile.NamedTemporaryFile()创建一个临时文件并vim打开它.但是,在Windows上,系统说:
该进程无法访问该文件,因为该文件正由另一个进程使用.
我想这是因为脚本当前正在使用该文件.
为什么它适用于Linux,如何让它在Windows上运行?
我以前遇到过这个问题。我的问题是我必须写入一个文件,然后使用该文件的名称作为命令中的参数。
这在 Linux 中起作用的原因是,正如@PM 2Ring在评论中所说,Linux 允许多个进程写入同一个文件,但 Windows 不允许。
有两种方法可以解决这个问题。
一种是创建一个临时目录并在该目录中创建一个文件。
# Python 2 and 3
import os
import tempfile
temp_dir = tempfile.mkdtemp()
try:
temp_file = os.path.join(temp_dir, 'file.txt')
with open(temp_file, 'w') as f:
pass # Create the file, or optionally write to it.
try:
do_stuff(temp_file) # In this case, open the file in an editor.
finally:
os.remove(file_name)
finally:
os.rmdir(temp_dir)
Run Code Online (Sandbox Code Playgroud)
# Python 3 only
import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
temp_file = os.path.join(temp_dir, 'file.txt')
with open(temp_file, 'w') as f:
pass # Create the file, or optionally write to it.
do_stuff(temp_file)
# with tempfile.TemporaryDirectory(): automatically deletes temp_file
Run Code Online (Sandbox Code Playgroud)
另一种方法是创建临时文件,delete=False以便当您关闭它时,它不会被删除,然后稍后手动删除它。
# Python 2 and 3
import os
import tempfile
fp = tempfile.NamedTemporaryFile(suffix='.txt', delete=False)
try:
fp.close()
do_stuff(fp.name)
finally:
os.remove(fp.name)
Run Code Online (Sandbox Code Playgroud)
这是一个可以创建文件的小上下文管理器:
import os
import tempfile
_text_type = type(u'')
class ClosedTemporaryFile(object):
__slots__ = ('name',)
def __init__(self, data=b'', suffix='', prefix='tmp', dir=None):
fp = tempfile.mkstemp(suffix, prefix, dir, isinstance(data, _text_type))
self.name = fp.name
if data:
try:
fp.write(data)
except:
fp.close()
self.delete()
raise
fp.close()
def exists(self):
return os.path.isfile(self.name)
def delete(self):
try:
os.remove(self.name)
except OSError:
pass
def open(self, *args, **kwargs):
return open(self.name, *args, **kwargs)
def __enter__(self):
return self.name
def __exit__(self, exc_type, exc_val, exc_tb):
self.delete()
def __del__(self):
self.delete()
Run Code Online (Sandbox Code Playgroud)
用法:
with ClosedTemporaryFile(suffix='.txt') as temp_file:
do_stuff(temp_file)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |