Python 2.5-根据查找列表中存储的值更新文本文件文件夹
我正在尝试编写一个脚本,该脚本将根据查找表更新文本文件文件夹。查找表包括文件名、旧路径、新路径。脚本在每个文本文件中查找文件名,如果有,它将用新路径更新同一行中的旧路径。代码是:Python 2.5-根据查找列表中存储的值更新文本文件文件夹,python,python-2.5,Python,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 W
# 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()
这一切似乎都正常工作,print语句末尾的5行找到了包含查找中的搜索字符串的正确行,但文件未更新
我已经阅读了尽可能多的关于文件打开模式和更新文件的内容,但没有明显的解决方案。我想问题是读/写同一个文件。我选择的路径是打开查找并嵌入要更改的文件循环。另一种方法是打开文件,然后循环查找
很高兴将更新后的文件写入另一个名称/文件夹,但问题是,如果在要更新的文件中循环,则根据查找更新该行,当到达查找的下一行时,它将覆盖以前的查找更改
任何想法都受到了感激。如果描述似乎很复杂,很乐意澄清目标不明显的任何领域
谢谢
保罗
返回字符串列表,并且您正在迭代这些字符串。因此,当您使用
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)
这是我用于测试的代码。它包含了科尔建议的很大一部分,所以我相信他的答案。我对Python非常陌生,因此代码可能非常漂亮,但它产生了我们所期望的结果
# 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()
代码有一些问题,我注意到的第一个主要问题是,您只使用Lookup.csv文件的最后一行。我是盲人吗?您在哪里写入更新或写入任何文件?该文件不会更新,因为您没有向其写入任何新内容。您当前正在尝试仅在内存中修改
line
,但还需要将结果分配给某个对象,result=line.replace(OldPath,NewPath)
Rob-抱歉,当代码粘贴到#Use的缩进中时,列表参数丢失,这和下面的所有行都应该在上面的for循环中。罗伯特/马丁,你们都是对的。我在下面添加了我最终使用的代码。Rob,谢谢你的代码。在2.5版本中,我得到错误“Warning:'with'将成为Python 2.6中的保留关键字”,因此我无法使用上面的语句
# 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()