Search code examples
pythonpython-os

Reading file in the same folder - Improvement?


i am writing an python script. I was having some problems to open the file. The error was always that system just can not find the file.

Because of that i tried get the active path... Replace backslash ... and so on....

Is there any improvements to work with the file in the same folder?

The Code

import os

# The name of the txt file that is in the same folder.
myFile = 'noticia.txt'

# Getting the active script
diretorio = os.path.dirname(os.path.abspath(__file__))

# Replace BackSlash and concatenate myFile
correctPath = diretorio.replace("\\", "/") + "/" + myFile

# Open file
fileToRead = open(correctPath, "r")

# Store text in a variable
myText = fileToRead.read()

# Print
print(myText)


Note:

The script is in the same folder of the txt file.


Solution

  • Is there any improvements to work with the file in the same folder?

    First off, please see PEP 8 for standard conventions on variable names.

    correctPath = diretorio.replace("\\", "/") + "/" + myFile
    

    While forward slashes are preferred when you specify a new path in your code, there is no need to replace the backslashes in a path that Windows gives you. Python and/or Windows will translate behind the scenes as necessary.

    However, it would be better to use os.path.join to combine the path components (something like correct_path = os.path.join(diretorio, my_file)).

    fileToRead = open(correctPath, "r")
    
    # Store text in a variable
    myText = fileToRead.read()
    

    It is better to use a with block to manage the file, which ensures that it is closed properly, like so:

    with open(correct_path, 'r') as my_file:
        my_text = my_file.read()