如何在Python中使用glob向文件名添加字符?
下面是一段代码。脚本从“Test”文件夹中获取输入文件,运行函数,然后在“Results”文件夹中输出同名文件(即如何在Python中使用glob向文件名添加字符?,python,character,glob,qgis,Python,Character,Glob,Qgis,下面是一段代码。脚本从“Test”文件夹中获取输入文件,运行函数,然后在“Results”文件夹中输出同名文件(即“Example\u Layer.shp”)。我如何设置它,使输出文件改为读取“Example_Layer(A).shp” 当前,您只需计算一次输出变量(由于您尚未定义任何fname,因此IMO无法使用该变量) 将语句移动到for循环中计算输出变量的位置,如下所示: #Set paths path_dir = home + "\Desktop\Test\\" path_res = p
“Example\u Layer.shp”)
。我如何设置它,使输出文件改为读取“Example_Layer(A).shp”
当前,您只需计算一次
输出
变量(由于您尚未定义任何fname
,因此IMO无法使用该变量)
将语句移动到for循环中计算输出变量的位置,如下所示:
#Set paths
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
def run():
#Set definitions
input = path_res + "/" + "input.shp"
#Set current path to path_dir and search for only .shp files then run function
os.chdir(path_dir)
for fname in glob.glob("*.shp"):
output = path_res + "/" + fname
run_function, input, output
run()
回答你的问题: 我如何设置它,使输出文件改为“Example_Layer(A).shp” 您可以使用将文件复制到新目录,使用
os.path.join将(a)
添加到每个文件名中。要加入路径和新文件名,请执行以下操作:
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
import os
import shutil
def run():
os.chdir(path_dir)
for fname in glob.glob("*.shp"):
name,ex = fname.rsplit(".",1) # split on "." to rejoin later adding a ("A")
# use shutil.copy to copy the file after adding ("A")
shutil.copy(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))
# to move and rename in one step
#shutil.move(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))
这是正确的。在风格上,我还建议使用字符串替换而不是字符串连接。非常感谢,我已经重新构建了我的脚本。但是,我接受了另一个答案,因为它关注的是如何重命名文件(我可能应该将问题的措辞改得更好,因此对此表示歉意)。非常感谢,你确实回答了我的问题:)@Joseph,很好,很高兴这有帮助:)如果你不想保留原始文件,可以使用shutil.move。再次感谢,我以前使用过shutil.move
和shutil.remove
,但我认为重命名文件对我来说会更安全=)@Joseph,不用担心,我只是想提一下。非常感谢Padraic!我正在测试它,它适用于大多数文件,因为有些文件仍在使用中,但这可能是由于脚本的另一部分。再次感谢你,老兄!
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
import os
import shutil
def run():
os.chdir(path_dir)
for fname in glob.glob("*.shp"):
name,ex = fname.rsplit(".",1) # split on "." to rejoin later adding a ("A")
# use shutil.copy to copy the file after adding ("A")
shutil.copy(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))
# to move and rename in one step
#shutil.move(fname,os.path.join(path_res,"{}{}{}".format(name,"(A)",ex)))