1

I am training Python, and I created a script that can save some data in a .txt file. I am following instructions from a video, and the "teacher" used PyCharm, I am on Visual Studio.

So the script checks if the file exist, if not, create a file with the exact name. The code of my script:

filename = 'desafio115.txt'
if not fileExist(filename):
    createFile(filename)

while True:
    menu.ui_menu()
    opt = int(input('Select Option: '))
    if opt == 1:
        readFile(filename)
    elif opt == 2:
        name = str(input('Name: '))
        age = leiaInt('Age: ')
        cadastrar(filename, name, age)

And the functions code:

def fileExist(file):
    try:
        a = open(file, 'rt', encoding='UTF-8')
        a.close()
    except FileNotFoundError:
        return False
    else:
        return True


def createFile(file):
    try:
        a = open(file, 'wt+', encoding='UTF-8')
        a.close()
    except:
        print('Error!!!')
    else:
        print(f'Arquivo {file} criado com sucesso!')


def readFile(file):
    try:
        a = open(file, 'rt', encoding='UTF-8')
    except:
        print('Erro! Arquivo não pode ser lido')
    else:  
        print('Pessoas cadastradas:'.center(40))
        for linha in a:
            dado = linha.split(';')
            dado[1] = dado[1].replace('\n', '')
            print(f' {dado[0]:<30} {dado[1]:>3} anos')
    finally:
        a.close()

The problem is: I am on Linux, and the path of the Python files is: 'Documents>Coding>Python Course>Part 3', but, the .txt are being created on "Python Course" folder, not inside the folder that the script is saved. How to change the path, in such a way that I can use this script in Windows too? In the video that I use as a guide, the teacher don't had this problem, with a very similar folder structure, but using MacOS and PyCharm. (Sorry about any typing errors, english is not my primary language)

ElSantAna
  • 11
  • 1
  • 2
    You never give a path to the directory where you want to write this file, so it will just write it to whatever your current working directory is (usually where your Python interpreter is running from), which I imagine is just the "Python Course" directory. – wkl Aug 16 '22 at 20:25
  • 1
    Do you know how to set your working directory, that is, the directory from which you *run* your Python script? – jjramsey Aug 16 '22 at 20:26
  • 1
    As @wkl suggested, you need to check your working directory. You can use `os.getcwd` - see documentation at https://docs.python.org/3/library/os.html#os.getcwd – Kelly Kuzemchak Aug 16 '22 at 20:29
  • As a side note, Pythonic code follows the "better to ask forgiveness than permission", rather than the "look before you leap" methodology your code is written in. See [here](https://stackoverflow.com/a/12270384/5763413) for the difference. In other words, there's no need to check if the file is there, instead just try and open it and catch exceptions accordingly. – blackbrandt Aug 16 '22 at 20:39

1 Answers1

1

Path separator


How to change the path, in such a way that I can use this script in Windows too?

Linux uses / for path separation, while Windows uses / and \.

For issues about cross-platform and character escaping, just use /.

Path setting

'Documents>Coding>Python Course>Part 3'

You want to create the file there? Just use os.chdir to CHange DIRectory.

import os
os.chdir("C://Users/YOUR_USERNAME/Documents/Coding/Python Course/Part 3")

This changes the working directory to what you want, just put it at the beginning of the program.

If you don't want to use this method, just run the interpreter from another directory if you launch it manually from a terminal.


You never give a path to the directory where you want to write this file, so it will just write it to whatever your current working directory is (usually where your Python interpreter is running from)

This explaination of the problem given by wkl is exaustive and I wanted to include it in my answer.

Read


FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
  • Minor correction, there are niche cases where Win will *allow* a forward slash as a path separator, but Win *does not use a forward slash*, it uses backslashes. Forward slash is an argument (flag) indicator; and for this reason (many moons ago) it was decided that rather than changing the arg parsers, a backslash was to be used as a path sep. (A design decision which has been the Bane of many of our lives). In fact it’s Python which allows us to use a proper path sep (forward slash) in scripts; not Win. – S3DEV Aug 16 '22 at 20:36
  • Additionally, rather than `chdir` to the path into which a file is to be saved, it’s more sustainable to simply provide the explicit path to the file location when saving the file. – S3DEV Aug 16 '22 at 20:39
  • About the second comment @S3DEV I would say *for sure*, I always do it, but it's more immediate to make as a change since this .txt file is mentioned too many times in the OP's code and I would have had to post the full changed code to be 100% clear. – FLAK-ZOSO Aug 16 '22 at 20:40
  • "You want to create the file there?" Yep, inside the folder "Part 3". Right, but I need to write the full path inside the os.chdir? How I do this to make the .py project compatible with Linux and Windows? Because you used a Windows path for example, and I am using Linux, but I also want to test the .py file in a Windows machine. – ElSantAna Aug 17 '22 at 16:01
  • It should work for both Linux and Windows with forward slash notation – FLAK-ZOSO Aug 17 '22 at 17:46
  • @FLAK-ZOSO worked well on Linux, thanks! But, I need to test on a Windows machine and another Linux machine, that have differents usernames. There is a way to do it? Ex: In my machine I used: ```os.chir('home/"myuser"/Documents/Coding/Curso Pyhton/Mundo 3/Desafios')``` , on a Windows machine, I need to know the name of the user? Or there is a parameter to the Python file locate the "Documents" folder of the system, or even ask for a path of the file? – ElSantAna Aug 18 '22 at 18:00
  • I think you should ask it in a different question, but anyway you can pass it as argument, if the other user doesn't know which one is their username just type "whoami" in their terminal. – FLAK-ZOSO Aug 18 '22 at 18:24