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)