PYTHON如何从父目录的文件夹中读取txt文件



我是python的新手,试图同时学习和编码,以测试我能做什么,我在课程中学习了java, javascript, php, html, css,所以我仍然记得基础知识。

我遇到了这个问题,几个小时后我还没有找到一个我能理解和喜欢的解决方案。

这是我的结构:

我的结构我想在test_input.py中读取test_input.txt,我想这样做是因为有一些字符串供用户使用,我希望这些字符串根据语言而变化。我想在。py文件旁边写。txt,但是每次函数生成字符串时,我都需要再次创建所有的语言文件夹,如果需要添加另一种语言,我也会在每个字符串出现时创建各种文件夹。

如果可能的话,我想要一个解决方案,读取项目内部本身得到。txt文件,因为我希望这个项目是一个。exe桌面程序。此外,python适合制作简单的桌面应用程序吗?我很期待学习未来的语言,就像我在java中学习android,但我想使用kotlyn,因为它"更好",所以我可以用java做这个项目,因为我在过去学过一些,但我想要"未来最常用的"。

如果我错了,请纠正我,所有这些都是关于看看我能做什么,以及如何,感谢帮助!!

如果我理解正确的话,您希望在py中加载和读取txt文件。如果是这种情况,就像我理解的那样,那么也许你想在这里遵循这个教程:https://www.pythontutorial.net/python-basics/python-read-text-file/

还有,你是否已经尝试打开/加载它了?如果是,你得到一个错误吗?大多数情况下,这是初学者的路径问题,所以请确保路径已经设置好。

欢呼

我从geeksforgeeks那里得到了这个脚本,它有多种形式的如何阅读。txt,我也给你留下了文档。

# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi n","This is Paris n","This is London n"] 

# n is placed to indicate EOL (End of Line)
file1.write("Hello n")
file1.writelines(L)
file1.close() #to change file access modes

file1 = open("myfile.txt","r+") 

print("Output of Read function is ")
print(file1.read())
print()

# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0) 

print( "Output of Readline function is ")
print(file1.readline()) 
print()

file1.seek(0)

# To show difference between read and readline
print("Output of Read(9) function is ") 
print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ") 
print(file1.readline(9))

file1.seek(0)
# readlines function
print("Output of Readlines function is ") 
print(file1.readlines()) 
print()
file1.close()

https://www.geeksforgeeks.org/reading-writing-text-files-python/

最新更新