2015-06-25 1 views
0

Я пытаюсь написать сценарий, который будет обновлять папку текстовых файлов на основе таблицы поиска. Таблица поиска - это имя файла, oldpath, новый путь. Скрипт просматривает каждый текстовый файл для имени файла, если он обновляет старый путь в той же строке с новым путем. Код:Python 2.5 - Обновить папку текстовых файлов из значений, хранящихся в списке поиска

# Import 
from array import * 
import glob 

# Specify the lookup table, to keep it simple drop it in with the workspaces 
Lookup = "./Lookup.csv" 

# Specify the 
Workspaces = glob.glob('./*.wor') 

# Open the Lookup table 
for line in open(Lookup).readlines(): 
    # Create the list to store the lookup parameters of the lookup line 
    LookupList = [] 
    # Split the lookup csv at the comma 
    for i in line.split(","): 
     #print i 
     LookupList.append(i) 
# Use the list parameters to populate variables (could use list parameters but 
# easier for now to assign to variable) 
FileName = LookupList[0] 
OldPath = LookupList[1] 
NewPath = LookupList[2] 

# We now have variables to use in the replace statement 
# Use the Workspaces Glob to loop through the workspaces 
for wor in Workspaces: 
    # Try to open the the first workspace (text file) 
    f = open(wor, 'r+') 
    # Loop through the open file 
    for line in f.readlines(): 
     # For each line check whether the current list value (FileName) is in the line 
     if '"' + OldPath + '"' in line: 
      print line 
      # Update the line, replacing the old path with the new path. 
      line.replace(OldPath, NewPath); 
    # Close the workspace file   
    f.close() 

Все, кажется, работает, как положено, в заявлении для печати 5 строк с конца нашел правильные строки, которые содержат строки поиска из поиска, но файл не обновляется.

Я читал столько, сколько могу найти в режимах открытия файлов и обновления файлов, но нет очевидного решения. Я думаю, проблема заключается в чтении/записи в тот же файл. Маршрут, который я выбрал, открывает поиск и встраивает файлы, которые нужно изменить. Альтернативой является открытие файла, а затем цикл через поиск.

С удовольствием записываем обновленный файл в другое имя/папку, проблема в том, что если вы прокручиваете файлы для обновления, обновите строку на основе поиска, когда вы перейдете к следующей строке поиска перезапишет предыдущее изменение.

Любые идеи с благодарностью получены. Aplogies, если описание кажется запутанным, с удовольствием прояснить любые области, где цель не очевидна.

Благодаря

Пол

+0

Есть несколько проблем с кодом, первый из которых я замечаю, что вы используете только последнюю строку файла Lookup.csv. –

+0

Я слепой? Где вы пишете обновление или записываете в любой файл? –

+0

Файл не обновляется, так как вы ничего не писали. В настоящее время вы пытаетесь изменить 'line' только в памяти, но вам также нужно будет присвоить результат чему-то: result = line.replace (OldPath, NewPath)' –

ответ

0
f.readines() 

возвращает список строк, и вы итерацию над этими строками. Итак, когда вы редактируете эту строку, используя

line.replace(...) 

Вы не изменяете текстовый файл. Скорее всего, вы изменяете строку, которую вы прочитали в

Ваш подход должен написать каждую строку списка темп, затем записать этот список временный в файл, например:.

f = open(wor, 'r+') 
new_lines = [] 
for line in f.readlines(): 

    if '"' + OldPath + '"' in line : 
     line.replace(OldPath, NewPath); 
    new_lines.append(line) 

f.close() 

file("path/to/your/new/or/temp/file","w") 
file.write("\n".join(new_lines)) 
file.close() 
0

Есть проблемы с тем, как вы добавляете LookupList, поскольку вы повторно назначаете его [], что делает его еще пустым, поэтому сохраняется только последняя итерация. Но в этом случае этот код для написания должен делать то, что вы намереваетесь сделать:

# We now have variables to use in the replace statement 
# Use the Workspaces Glob to loop through the workspaces 
for wor in Workspaces: 
    # Handles opening and closing of input and output files 
    with open(wor, 'r'),open("new_" + wor,'w') as infile,outfile: 
     # Loop through the input file 
     for line in infile.readlines(): 
      # For each line check whether the current list value (FileName) is in the line 
      if '"' + OldPath + '"' in line: 
       print line 
       # Update the line, replacing the old path with the new path. 
       line.replace(OldPath, NewPath); 
      outfile.write(line) 
+0

Роб, спасибо за код. В 2.5 Я получаю сообщение об ошибке «Предупреждение:« с »станет зарезервированным ключевым словом в Python 2.6, поэтому я не смог бы использовать вышеизложенное. – Moulder

+0

Попробуйте следующее: от __future__ import with_statement –

0

Это код, который я использовал, который работал для тестирования. В нем содержится большой кусок предложения Хола, поэтому я прислал ему ответ. Я довольно новичок в Python, поэтому код может быть красотой 5 ярдов, но он дает результаты, которые мы ищем.

# Import 
from array import * 
import glob 

# Specify the lookup table, to keep it simple drop it in with the workspaces 
Lookup = "./Lookup.csv" 

# Specify the list of workspaces (text files to update) 
Workspaces = glob.glob('./*.wor') 

# Open the Lookup table 
for line in open(Lookup).readlines(): 
    # Create the list to store the lookup parameters of the lookup line 
    LookupList = [] 
    # Split the lookup csv at the comma 
    for i in line.split(","): 
     # Add items to the lookup list 
     LookupList.append(i) 

    # Assign the list value to a variable (could skip assigning to variable), 
    # strip CR from value or it will add it to the output string 
    FileName = LookupList[0].strip() 
    NewPath = LookupList[1].strip() 

    # Loop through the workspaces 
    for wor in Workspaces: 

     # Open the workspace 
     f = open(wor, 'r+') 

     # Create list 
     WorList = [] 

     # Read through the workspace and use it to populate the list 
     for line in f.readlines(): 
      WorList.append(line) 
     f.close() 

     # Loop through the workspace list looking for the FileName string (from the lookup list) 
     for position, item in enumerate(WorList): 
      if " " + FileName + " " in item: 
       # If the filename is found then create a string with the new file name in the old row structure 
       Newval = "Open Table " + '"'+ NewPath + '" ' + "As " + FileName + " Interactive\n" 
       # Update the value in the list based on the list position 
       WorList[position] = Newval; 

     # Open the output file (this is the same as the original input file) 
     file=open(wor,"w") 

     # Work through the list and write it to the file 
     for s in WorList: 
      file.write(s) 
     file.close() 
Смежные вопросы