简体   繁体   English

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

[英]Need help creating a txt file in a folder which, is in the same directory

I'm pretty new to python. 我是python的新手。 I have a homwork problem where we need to analyze corpora and then compare them. 我有一个相互矛盾的问题,我们需要分析语料库,然后进行比较。 We also have to save the files as a .txt file after is has been processed with an attribute, the size. 使用属性(大小)处理后,我们还必须将文件另存为.txt文件。

So I need to create a .txt file in a seperate folder called trigram-models. 因此,我需要在名为trigram-models的单独文件夹中创建一个.txt文件。 This folder is in the same directory as my python file. 该文件夹与我的python文件位于同一目录中。 I think i have to use the os module but i'm not sure how. 我想我必须使用os模块,但是我不确定如何使用。

Here is my code: 这是我的代码:

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)

To create a directory, I would use the following format which relies on a try / catch and prevents an error if the directory already exists: 要创建目录,我将使用以下格式,该格式依赖于try / catch并防止错误(如果目录已存在):

dirName = 'tempDir'

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

To change your directory you can use the following: 要更改目录,可以使用以下命令:

os.chdir(directoryLocation)

I recommend reading chapter 8 in automating the boring stuff with python . 我建议阅读第8章中的使用python自动完成无聊的工作

I hope this helps. 我希望这有帮助。 If you have any questions please don't hesitate to ask. 如有任何疑问,请随时提出。

First of all, be sure to indent all the code in your method for it to be appropriately enclosed. 首先,请确保缩进方法中的所有代码,以使其适当地包含在内。

You are also passing relative paths ( datafolder, profilefolder ) for your folders as method arguments, so you should use them inside the method instead. 您还将传递文件夹的相对路径( datafolder,profilefolder )作为方法参数,因此您应该在方法内部使用它们。

Lastly, to create a file in a folder, I would recommend using the following algorithm: 最后,要在文件夹中创建文件,我建议使用以下算法:

file_path = '/'.join(profilefolder, newname)

with open(file_path, 'w') as ouf:
    ouf.write(endtable)

You will probably need to replace "endtable" with a string representation of your data. 您可能需要用数据的字符串表示形式替换“ endtable”。

Hope it helps. 希望能帮助到你。

Your function is not using the argument profileFolder , where you specify the name of the output directory. 您的函数未使用参数profileFolder ,在这里您指定输出目录的名称。 So first of all you should use this information for creating a folder before processing your files. 因此,在处理文件之前,首先应使用此信息来创建文件夹。

So first thing would be to create this output directory. 因此,第一件事就是创建此输出目录。 Second is to save your files there, and to do that you need to append the file name to the output directory. 其次是将文件保存在此处,然后需要将文件名附加到输出目录。 Something like this: 像这样:

def make_profiles(data_folder, output_folder, size):    

    filelist = []
    for file in os.listdir(data_folder):
        filelist.append(file)

    # Create output folder
    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

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

        splitname = str(file).split('-')

        # Create new file by appending name to output_folder
        newname = os.path.join(output_folder, splitname[0] + "." + str(size) + '.txt')


    return (endtable)

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

Note that you can also specify the relative folder name (ie "trigram-models" only) and then create the output directory by appending this name to the current path: 请注意,您还可以指定相对文件夹名称(即仅“ trigram-models”),然后通过将此名称附加到当前路径来创建输出目录:

output_folder = os.path.join(os.getcwd(), output_folder)

Also (not related to the question) this piece of code could be optimized: 同样(与问题无关),可以优化以下代码:

filelist = []
for file in os.listdir(data_folder):
    filelist.append(file)

os.listdir already returns a list, so you could directly write: os.listdir已经返回一个列表,因此您可以直接编写:

filelist = os.listdir(data_folder)

But since you're interested in the absolute path of each file you could better do: 但是,由于您对每个文件的绝对路径都感兴趣,因此最好执行以下操作:

filelist = [os.path.abspath(f) for f in os.listdir(data_folder)]

where you basically take each file returned by os.listdir and you append its absolute path to your file list. 在这里,您基本上获取了os.listdir返回的每个文件,并将其绝对路径附加到文件列表中。 Doing this you could avoid the line filen = "./training/"+file . 这样做可以避免filen = "./training/"+file这行。

So in the end your code should look something like this: 因此,最终您的代码应如下所示:

def make_profiles(data_folder, output_folder, size):    

    filelist = [os.abspath(f) for f in os.listdir(data_folder)]

    # Create output folder
    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

    for file in filelist:           
        splitname = str(file).split('-')

        # [...add other pieces of code]

        # Create new file by appending name to output_folder
        newname = os.path.join(output_folder, splitname[0] + "." + str(size) + '.txt')

        # [...add other pieces of code]
    return (endtable)

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

As to clarify on toti08's answer, you should replace os.absdir with os.path.absdir. 为了澄清toti08的答案,您应该将os.absdir替换为os.path.absdir。

filelist = [os.path.abspath(f) for f in os.listdir(data_folder)]

instead of 代替

filelist = [os.abspath(f) for f in os.listdir(data_folder)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 需要帮助在 Python 中创建 txt 日志文件 - Need help creating a txt log file in Python 需要帮助删除txt文件中的重复行 - Need help deleting repeating lines in txt file 需要帮助来创建一个Python脚本,该脚本从txt文件中读取主机名,对主机名执行ping操作,解析IP并将其打印到另一个文本文件 - Need help creating a Python script that reads hostnames from a txt file, pings the hostname, resolves the IP and prints it to another text file Python在同一文件夹中调用.txt文件 - Python calling .txt file in same folder 在与 .py 相同的文件夹中打开 a.txt 文件不起作用 - opening a .txt file in same folder as .py not working 需要帮助格式化 .txt 文件并放入数据框中 - Need help formatting a .txt file and placing into a data frame 我需要帮助将 txt 文件中的值添加到一组元组 - I need help adding values in a txt file to a set of tuples Python 3.3-需要帮助,编写来自.txt数据的.png文件 - Python 3.3 - Need help writing a .png file with data from a .txt Python3 从文件 txt 文件目录列表创建 JSON - Python3 creating JSON from file txt file directory listing 我需要帮助在 Pandas 中创建一个聚合在一个列上的 groupby - I need help creating a groupby in Pandas which aggregates on one column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM