gpt4 book ai didi

python - 需要帮助在同一目录中的文件夹中创建 txt 文件

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:49 24 4
gpt4 key购买 nike

我对Python还很陌生。我有一个家庭作业问题,我们需要分析语料库然后比较它们。在使用属性(大小)处理后,我们还必须将文件保存为 .txt 文件。

所以我需要在名为 trigram-models 的单独文件夹中创建一个 .txt 文件。该文件夹与我的 python 文件位于同一目录中。我想我必须使用 os 模块,但我不知道如何使用。

这是我的代码:

from langdetect import read_trigrams, trigram_table, write_trigrams
import os

def make_profiles(datafolder, profilefolder, size):

filelist = []
for file in os.listdir('./training'):
filelist.append(file)
print(filelist)

for file in filelist:
filen = "./training/"+file
print("fi", filen)

maketable = trigram_table(filen, size)

readdata = read_trigrams(filen)
#print("re", readdata)

splitname = str(file).split('-')
newname = splitname[0] + "." + str(size) + '.txt'

endtable = write_trigrams(readdata, newname)

return (endtable)

make_profiles("./training", "./trigram-models", 20)

最佳答案

要创建目录,我将使用以下格式,该格式依赖于 try/catch 并在目录已存在时防止错误:

dirName = 'tempDir'

try:
# Create target Directory
os.mkdir(dirName)
print("Directory " , dirName , " Created ")
except FileExistsError:
print("Directory " , dirName , " already exists")

要更改目录,您可以使用以下命令:

os.chdir(directoryLocation)

我建议阅读chapter 8 in automating the boring stuff with python .

我希望这有帮助。如果您有任何疑问,请随时询问。

关于python - 需要帮助在同一目录中的文件夹中创建 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56145159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com