您如何检查文件是否存在?

时间:2019-12-06 00:09:26

标签: python python-3.x python-2.7

所以我正在尝试为RLE程序编码。我需要压缩和解压缩文件,但是我很难检查文件是否存在。你能帮我这个忙吗?

这是我到目前为止的编程:

file2 = input('Enter name of file containing the RLE compressed data: ')
# takes the name of the file
    if file2.exist():
        text = open(file2, 'r')  # opens the file and reads it only    
        decode = ''
        count = ''
        data = input('Enter the name of the file to be compressed: ')
        for char in data:
            if char.isdigit():  # numerical char apears 
                 # isdigit() checks if it contain digits; if yes or no
                 count += char  # its added to the count
            else:  # new char appears
                 decode += char * int(count) 
                 # ^ decompress the char according to the count num
                 count = ''  # saves the new count num
     else:
        print('File name not found.')

我知道我需要修复显示为data = input('Enter the name of the file to be compressed: ')的部分,但稍后会修复文件部分。我有点知道如何做。

2 个答案:

答案 0 :(得分:0)

Python喜欢通过异常处理来处理这种情况:

try:
    fin = open(file2, 'r')  # opens the file and reads it only
except FileNotFoundError:
    print("file doesn't exist")

该原则称为EAFP:要求宽恕比允许(https://docs.quantifiedcode.com/python-anti-patterns/readability/asking_for_permission_instead_of_forgiveness_when_working_with_files.html)更容易。

主要优点是可读性强和简洁的编码风格:例如,您可以立即区分确定程序流程的常规条件和特殊情况。如果不经常发生异常,则效率也有一点优势。

答案 1 :(得分:0)

  

您可以使用os.path模块检查文件是否存在。该模块可用于Python 2和3。

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")