搜索,替换文本并根据Python中的文档中的文本进行保存

时间:2016-11-12 15:27:27

标签: python file python-3.x operating-system rename

所有,我刚刚开始使用python,我认为这可能是一个好时机,看看它是否可以帮助我自动完成我必须完成的许多重复任务。

我正在使用我在Gethub上找到的脚本来搜索和替换,然后编写一个名为output.txt的新文件。它工作正常,但由于我有很多这些文件,我需要能够根据最终修改文档中的文本命名不同的名称。

为了使这更加困难,文件的名称基于我将用文本修改文本。

所以,基本上在我运行这个脚本之后,我有一个文件位于C:\ Program Files(x86)\ Python35-32 \ Scripts \ Text_Find_and_Replace \ Result,其名称为output.txt,在此修改后的新文件中想根据文件特定行中的文本命名。所以在output.txt的修改文件中,我想让它将文件重命名为第35行的纯文本。

我已经找到了如何使用

读取文件中的行
import linecache
line = linecache.getline("readme.txt", 1)
line
>>> line
'This is Python version 3.5.1\n'

我只需要弄清楚如何根据变量“line”重命名文件 有任何想法吗?

#!/usr/bin/python

import os
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:\Program Files (x86)\Python35-        32\Scripts\Text_Find_and_Replace\information/replacingvalues.txt", 'r')
 #Text_Find_and_Replace\Result\output.txt This is the dir and the sum or    final document
output = open("C:\Program Files (x86)\Python35-32\Scripts\Text_Find_and_Replace\Result\output.txt", '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:\Program Files (x86)\Python35-   32\Scripts\Text_Find_and_Replace\Field/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:\Program Files (x86)\Python35-  32\Scripts\Text_Find_and_Replace\Test/remedy line 1.ahk", 'r') as myfile:
    inline = myfile.read()

#orig code
##with open("C:\Program Files (x86)\Python35-    32\Scripts\Text_Find_and_Replace\Test/input.txt", 'r') as myfile:
##    inline = myfile.read()

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;

我想出了......

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())

linecache.clearcache()

0 个答案:

没有答案