我希望根据文件是否已经存在而写入文件,只有在文件尚不存在时才写入(实际上,我希望继续尝试文件,直到找到不存在的文件).
以下代码显示了潜在攻击者可以插入符号链接的方式,如本文所述,在文件测试和正在写入的文件之间.如果代码以足够高的权限运行,则可能会覆盖任意文件.
有什么方法可以解决这个问题吗?
import os
import errno
file_to_be_attacked = 'important_file'
with open(file_to_be_attacked, 'w') as f:
f.write('Some important content!\n')
test_file = 'testfile'
try:
with open(test_file) as f: pass
except IOError, e:
# symlink created here
os.symlink(file_to_be_attacked, test_file)
if e.errno != errno.ENOENT:
raise
else:
with open(test_file, 'w') as f:
f.write('Hello, kthxbye!\n')
Run Code Online (Sandbox Code Playgroud) 我写了一个脚本来读取python中的文本文件.
这是代码.
parser = argparse.ArgumentParser(description='script')
parser.add_argument('-in', required=True, help='input file',
type=argparse.FileType('r'))
parser.add_argument('-out', required=True, help='outputfile',
type=argparse.FileType('w'))
args = parser.parse_args()
try:
reader = csv.reader(args.in)
for row in reader:
print "good"
except csv.Error as e:
sys.exit('file %s, line %d: %s' % (args.in, reader.line_num, e))
for ln in args.in:
a, b = ln.rstrip().split(':')
Run Code Online (Sandbox Code Playgroud)
我想检查文件是否存在而不是空文件但是这段代码给了我一个错误.
我还想检查程序是否可以写入输出文件.
命令:
python script.py -in file1.txt -out file2.txt
Run Code Online (Sandbox Code Playgroud)
错误:
good
Traceback (most recent call last):
File "scritp.py", line 80, in <module>
first_cluster = clusters[0]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud) 我知道如何创建文件,但在这种情况下,它会覆盖所有数据:
import io
with open('text.txt', 'w', encoding='utf-8') as file:
file.write('text!')
Run Code Online (Sandbox Code Playgroud)
在*nix我可以做的事情:
#!/bin/sh
if [ -f text.txt ]
#If the file exists - append text
then echo 'text' >> text.txt;
#If the file doesn't exist - create it
else echo 'text' > text.txt;
fi;
Run Code Online (Sandbox Code Playgroud) 我有一个包含以下子目录的目录:
从folder_001到folder_100
但是,我需要进行测试,因为某些目录可能会丢失。以下是实现此目的的最佳方法。似乎有点long。
>>> l = []
>>> for i in l:
... for f in os.listdir('.'):
... if not os.path.exists(i):
... os.mkdir(i)
...
Run Code Online (Sandbox Code Playgroud)
谢谢。