-1

so I am trying to code for an RLE program. I need to compress and decompress files, but I struggled to check if a file exists or not. can you help me with this please!

this is my programming so far:

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.')

I know that I need to fix the part where it says data = input('Enter the name of the file to be compressed: ') but I will do it later after fixing the file part. I kind of have an idea of how to do it.

  • 2
    Does this answer your question? [How do I check whether a file exists without exceptions?](https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions) – Guimoute Dec 06 '19 at 00:45
  • not really; l did look there before. l got my answer now , thanks tho – Lucy DiAz_16 Dec 06 '19 at 01:03
  • @LucyDiAz_16 not really? The answer you have marked correct is similar to https://stackoverflow.com/a/8876254/6622587 – eyllanesc Dec 06 '19 at 02:05

2 Answers2

1

Python likes to approach such situations via exception handling:

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

This principle is called EAFP: it's easier to ask for forgiveness than permission (https://docs.quantifiedcode.com/python-anti-patterns/readability/asking_for_permission_instead_of_forgiveness_when_working_with_files.html).

The advantage is mostly readability and a clean coding style: e.g., you can immediately distinguish between regular conditions that determine program flow and exceptional situations. There is also a slight advantage in efficiency, if the exception doesn't happen very often.

sammy
  • 857
  • 5
  • 13
1

You can use the os.path module to check if a file exists. The module is available for both Python 2 and 3.

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")
Renuka Deshmukh
  • 998
  • 9
  • 16