我正在写一个python脚本。我在打开文件时遇到了一些问题。错误始终是系统无法找到文件。
因此,我尝试获取活动路径...替换反斜杠...依此类推...。
使用同一文件夹中的文件是否有任何改进?
import os
# The name of the txt file that is in the same folder.
myFile = 'noticia.txt'
# Getting the active script
diretorio = os.path.dirname(os.path.abspath(__file__))
# Replace BackSlash and concatenate myFile
correctPath = diretorio.replace("\\", "/") + "/" + myFile
# Open file
fileToRead = open(correctPath, "r")
# Store text in a variable
myText = fileToRead.read()
# Print
print(myText)
该脚本位于txt文件的同一文件夹中。
使用同一文件夹中的文件是否有任何改进?
首先,请参阅PEP 8以获取有关变量名称的标准约定。
correctPath = diretorio.replace("\\", "/") + "/" + myFile
当在代码中指定新路径时,首选使用正斜杠,但是无需替换Windows提供的路径中的反斜杠。Python和/或Windows将在必要时在后台进行翻译。
但是,最好os.path.join
结合使用路径组件(类似correct_path = os.path.join(diretorio, my_file)
)。
fileToRead = open(correctPath, "r")
# Store text in a variable
myText = fileToRead.read()
最好使用with
块来管理文件,以确保正确关闭文件,如下所示:
with open(correct_path, 'r') as my_file:
my_text = my_file.read()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句