相关疑难解决方法(0)

如何检查文件是否存在而没有例外?

如何在不使用该try语句的情况下查看文件是否存在?

python file file-exists

5290
推荐指数
41
解决办法
372万
查看次数

当且仅当python不存在时才安全地创建文件

我希望根据文件是否已经存在而写入文件,只有在文件尚不存在时才写入(实际上,我希望继续尝试文件,直到找到不存在的文件).

以下代码显示了潜在攻击者可以插入符号链接的方式,如本文所述,在文件测试和正在写入的文件之间.如果代码以足够高的权限运行,则可能会覆盖任意文件.

有什么方法可以解决这个问题吗?

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

88
推荐指数
2
解决办法
6万
查看次数

如何检查文本文件是否存在并且在python中不为空

我写了一个脚本来读取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)

python filepath python-3.x

21
推荐指数
2
解决办法
3万
查看次数

在Python中将文本附加到文件

  1. 如何检查文件是否存在?
  2. 如何将文本附加到文件?

我知道如何创建文件,但在这种情况下,它会覆盖所有数据:

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)

python io

7
推荐指数
1
解决办法
3万
查看次数

如何检查python中是否存在文件?

可能重复:
检查文件是否存在的Pythonic方法?

如何检查python中是否存在文件?

在Windows中编写脚本

python windows file

3
推荐指数
2
解决办法
1万
查看次数

Python-创建列表中不存在的目录

我有一个包含以下子目录的目录:

从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)

谢谢。

python

0
推荐指数
1
解决办法
172
查看次数

标签 统计

python ×6

file ×2

file-exists ×1

filepath ×1

io ×1

python-3.x ×1

windows ×1