我对python很陌生,我正在研究一种打开名为acne.txt的文件的方法,该文件位于我的定义文件夹中,与我的代码位于同一个python34文件夹中。
我为同样的代码编写的代码是:
NN_is = [word for word,pos in tagged_sent if pos == 'NN']
print(NN_is[0])
searchfile = open(r"define/NN_is[0].txt", "r")
file_contents = searchfile.readlines()
searchfile.close()可变的NN_is当印刷产生痤疮。有人能帮我解决这个问题吗。
提前谢谢你。
发布于 2016-05-17 10:12:39
使用os.path.join()连接目录和文件名,并使用str.format()构造文件名的字符串:
import os.path
path = os.path.join('define', '{}.txt'.format(NN_is[0]))
with open(path) as searchfile:
file_contents = searchfile.readlines()
...我还建议您在with语句中打开该文件。这可以确保文件始终被关闭,即使有错误。这也很方便,因为您不需要显式关闭文件--当with语句超出作用域时,它将被关闭。
https://stackoverflow.com/questions/37272991
复制相似问题