【问题标题】:How to copy one file based on a variable如何根据变量复制一个文件
【发布时间】:2017-03-27 13:13:44
【问题描述】:

我正在构建一个 python 脚本,基本上通过搜索和替换文件中的单词来编辑大量文件。

有一个原始文件名为:C:\python 3.5/remedy line 1.ahk

有一个文件包含我要在原始文档中替换的词(搜索词)和一个文本文件,其中包含我想放入最终文档中的新词列表。

脚本然后运行并完美运行。然后根据最终文本文件中的一行创建并命名最终文档(代码从第 72 行开始)。一种让我可以通过查看来判断最终产品是什么的方法。该文件最初命名为output = open("C:\python 3.5\output.ahk", 'w'),后来在脚本中根据脚本中的第 37 行对其进行了重命名。一切正常。

所以我似乎无法弄清楚的看似简单的部分是如何获取这个文件并将其移动到它所属的目录。该目录是基于文件获取其名称的同一行创建的(代码从第 82 行开始)。我如何简单地将我的文件移动到由脚本创建的目录中,即基于一个变量(代码从第 84 行开始),因此文件的名称基于一个变量。

    import shutil
    #below is where your modified file sits, before we move it into it's own     directory named dst, based on a variable #mainnewdir 
    srcdir = r'C:\python 3.5/'+(justfilename)
    dst = (mainnewdir)+(justfilename)
    shutil.copyfile(src, dst)
  1. 为什么会在代码中多出\
  2. 如果我使用 /\ 斜杠,为什么它似乎没有给我一个错误?

这是整个代码,就像我说的只有最后一部分移动文件不起作用:

    import os
    import linecache
    import sys
    import string
    import re

    ## information/replacingvalues.txt this is the text of the values you         want in your final document
    #information = open("C:\python 3.5\replacingvalues.txt", 'r')
    information = open("C:\python 3.5/replacingvalues.txt", 'r')
    # information = open("C:\Program Files (x86)\Python35-        32\Scripts\Text_Find_and_Replace\information/replacingvalues.txt",

    # Text_Find_and_Replace\Result/output.txt This is the dir and the sum or         final document


    # output = open("C:\python 3.5\output.ahk", 'w')
    createblank = open ("C:\python 3.5/output.ahk", 'w')
    createblank.close()
    output = open("C:\python 3.5\output.ahk", 'w')
    # field = open("C:\Program Files (x86)\Python35-        32\Scripts\Text_Find_and_Replace\Field/values.txt"
    # Field is the file or words you will be replacing
    field = open("C:\python 3.5/values.txt", 'r')


    # modified code for autohot key
    # Text_Find_and_Replace\Test/remedy line 1.ahk is the original doc you want modified
    with open("C:\python 3.5/remedy line 1.ahk", 'r') as myfile:
    inline = myfile.read()
    ## remedy line 1.ahk

    informations = []
    fields = []
    dictionary = {}
    i = 0

    for line in information:
        informations.append(line.splitlines())

    for lines in field:
        fields.append(lines.split())
        i = i + 1;

    if (len(fields) != len(informations)):
        print("replacing values and values have different numbers")
        exit();
    else:
        for i in range(0, i):
            rightvalue = str(informations[i])
            rightvalue = rightvalue.strip('[]')
            rightvalue = rightvalue[1:-1]

            leftvalue = str(fields[i])
            leftvalue = leftvalue.strip('[]')
            leftvalue = leftvalue.strip("'")

            dictionary[leftvalue] = rightvalue

            robj = re.compile('|'.join(dictionary.keys()))
            result = robj.sub(lambda m: dictionary[m.group(0)], inline)

       output.write(result)
        information.close;
        output.close;
        field.close;
        output.close()

    import os
    import linecache
    linecache.clearcache()
    newfilename= linecache.getline("C:\python 3.5/remedy line 1.txt",37)
    filename = ("C:\python 3.5/output.ahk")
    os.rename(filename, newfilename.strip())
    #os.rename(filename, newfilename.strip()+".ahk")
    linecache.clearcache()


    ############## below will create a new directory based on the the word         or words in line 37 of the txt file.

    newdirname= linecache.getline("C:\python 3.5/remedy line 1.txt",37)
    #newpath = r'C:\pythontest\automadedir'
    #below removes the /n ie new line raw assci
    justfilename = (newdirname).strip()
    #below removes the .txt from the rest of the justfilename..
    autocreateddir = (justfilename).strip(".txt")
    # below is an example of combining a string and a variable
    # below makes the variable up that will be the name of the new directory         based on reading line 37 of a text file above

    mainnewdir= r'C:\pythontest\automadedir/'+(autocreateddir)
    if not os.path.exists(mainnewdir):
        os.makedirs(mainnewdir)

        linecache.clearcache()
    # ####################################################
    #below is where your modified file sits, before we move it into it's own         directory named dst, based on a variable #mainnewdir
    srcdir = r'C:\python 3.5/'+(justfilename)
    dst = (mainnewdir)+(justfilename)
    shutil.copyfile(src, dst)

【问题讨论】:

  • 你在这里问了两个问题,一个关于反斜杠表示,一个关于复制文件,这两个问题都可以通过一些非常基础的研究来回答。另请注意,这不是论坛,因此您的大部分内容都不合适;见How to Ask
  • 我建议你也使用os.path.join()函数来构建文件名。

标签: python search replace move


【解决方案1】:

反斜杠没有自己的想法。

当您按原样粘贴 Windows 路径时,它们包含 \nr\b\x\v\U(python 3),(请参阅table here其中),您只是在使用转义序列而没有注意到它。

当转义序列不存在时(例如\p),它可以工作。但是当已知文件名通常无效时。这解释了问题的明显随机性。

为了能够安全地粘贴 windows 路径而不更改/转义它们,只需使用 raw 前缀:

my_file = r"C:\temp\foo.txt"

所以反斜杠不会被解释。但是有一个例外:如果字符串以反斜杠结尾,您仍然必须将其加倍。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    相关资源
    最近更新 更多