创建文件目录的.txt文件

时间:2017-04-27 21:13:08

标签: python python-2.7

我正在尝试在某个位置创建文件目录的.txt文件,删除前缀并保存文本文件。

我使用os.walk模块将位置目录列表构建到.txt文件中。我总是得到目录的文本文件。

在下一个代码块中删除这些目录行的前缀的部分不起作用。它创建了自己的.txt文件(因为它应该),但它总是空的。

如果有一个解决方案可以在一个.txt文件和一个代码块中完成所有这些工作,那就更好了!

这是我到目前为止所做的,为了隐私,我使用虚拟目录。

 import os
    from datetime import datetime

    # this is to create a filename with the timestamp_directory_list for a .txt file
    now = datetime.now()
    filename = datetime.now().strftime("%Y_%m_%d_%H_%M_%S_directory_list.txt")


    # uses os module to walk the directories and files 
# within a given location, then writes it line by line to a .txt file
    with open(filename, "w") as directory_list:
        for path, subdirs, files in os.walk(r"C:/Users"):
            for filenameX in files:
                f = os.path.join(path)
                directory_list.write(str(f) + os.linesep)


    # Open up .txt file, read a line, trim the prefix, then save it
    # this is to create a filename with the timestamp_directory_list for a .txt file
    trim = datetime.now().strftime("%Y_%m_%d_%H_%M_%S_trimmed_directories.txt")

    def remove_prefix(text, prefix):
        # Remove prefix from supplied text string
        if prefix in text:
            return text[len(prefix):]
        return text

    with open(filename, "r") as trim_input, \
        open(trim, "a") as trim_output:

        for line in trim_input:
            print line
            if "C" in line:
                print line
                trim_output = remove_prefix(trim_input, 'C')
                trim_output.write(line+ os.linesep) 

1 个答案:

答案 0 :(得分:0)

你混淆了变量名,实际上我希望如果运行它会引发一些异常。

  • 输出文件和修剪后的行<{1}}
  • 您正在“input_file_object”上调用trim_output而不是remove_prefix
  • 你得到修剪过的行(覆盖,我认为,输出文件参考),但你把(未修剪)行写到输出文件

你的代码应该是

line

稍后编辑: 为了使代码的行为与初始描述中所述的相同,“if”不应该出现,并且代码缩进一级

with open(filename, "r") as trim_input, \ open(trim, "a") as trim_output: for line in trim_input: print line if "C" in line: # this if is a bit useless you have an another if inside the remove_prefix, # also you are skyping all the lines without prefix print line trimmed_line = remove_prefix(line, 'C') trim_output.write(trimmed_line+ os.linesep) 也有缺陷

remove_prefix

应该是

def remove_prefix(text, prefix):
    # Remove prefix from supplied text string
    if prefix in text: 
        # if prefix is "C", this is true for "Ctest" and also for "testC"
        return text[len(prefix):] # but it removes the first chars
    return text