简体   繁体   English

将 a.txt 文件保存在特定路径中

[英]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.我正在训练 Python,我创建了一个脚本,可以将一些数据保存在 .txt 文件中。 I am following instructions from a video, and the "teacher" used PyCharm, I am on Visual Studio.我按照视频中的说明进行操作,“老师”使用了 PyCharm,我在 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.问题是:我在 Linux 上,Python 文件的路径是:'Documents>Coding>Python Course>Part 3',但是,.txt 是在“Python Course”文件夹中创建的,而不是在脚本已保存。 How to change the path, in such a way that I can use this script in Windows too?如何更改路径,以便我也可以在 Windows 中使用此脚本? 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.在我用作指导的视频中,老师没有这个问题,文件夹结构非常相似,但使用的是 MacOS 和 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?如何更改路径,以便我也可以在 Windows 中使用此脚本?

Linux uses / for path separation, while Windows uses / and \ . Linux 使用/进行路径分离,而 Windows 使用/\

For issues about cross-platform and character escaping, just use / .对于跨平台和字符 escaping 的问题,只需使用/

Path setting路径设置

'Documents>Coding>Python Course>Part 3' '文档>编码>Python 课程>第 3 部分'

You want to create the file there?你想在那里创建文件吗? Just use os.chdir to CHange DIRectory .只需使用os.chdir更改目录

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 )您永远不会给出要写入此文件的目录的路径,因此它只会将其写入您当前的工作目录(通常是 Python 解释器运行的位置

This explaination of the problem given by wkl is exaustive and I wanted to include it in my answer. wkl对问题的解释非常详尽,我想将其包含在我的答案中。

Read


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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