简体   繁体   中英

Save a .txt file in specific path

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)

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


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM