Python 2.5 - 根据存储在查找列表中的值更新文本文件的文件夹

Python 2.5 - Update folder of text files from values stored in a lookup list

我正在尝试编写一个脚本来根据查找更新文本文件的文件夹 table。查找 table 是文件名、旧路径、新路径。该脚本在每个文本文件中查找文件名,如果存在,它会在同一行中用新路径更新旧路径。代码是:

# 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 行已找到包含查找中的搜索字符串的正确行,但文件未更新。

我已经阅读了尽可能多的关于文件打开模式和更新文件的内容,但没有明显的解决方案。我想问题是 reading/writing 到同一个文件。我选择的路线是打开查找并嵌入要更改的文件循环。另一种方法是打开文件,然后循环查找。

很高兴将更新后的文件写到另一个 name/folder,问题是如果您循环遍历要更新的文件,当您到达下一行时,根据查找更新行查找将覆盖以前的查找更改。

非常感谢收到任何想法。如果描述看起来令人费解,我们深表歉意,很乐意澄清任何目标不明显的地方。

谢谢

保罗

f.readines()

returns 一个字符串列表,您正在迭代这些字符串。因此,当您使用

对该字符串进行编辑时
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()

您附加 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)

这是我用于测试的代码。它包含了 Khol 的大部分建议,因此我将答案归功于他。我对 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()