我想将当前工作目录中扩展名为.asc
的所有文件合并到名为outfile.asc
的文件中
我的问题是,我不知道如何排除特定的文件("BigTree.asc"
),如果目录中有一个"outfile.asc"
,如何覆盖现有的文件
if len(sys.argv) < 2:
print("Please supply the directory of the ascii files and an output-file as argument:")
print("python merge_file.py directory outfile")
exit()
directory = sys.argv[1]
os.chdir(directory)
currwd = os.getcwd()
filename = sys.argv[2]
fileobj_out = open(filename, "w")
starttime = time.time()
read_files = glob.glob(currwd+"\*.asc")
with open("output.asc", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
if f == "BigTree.asc":
continue
else:
outfile.write(infile.read())
endtime = time.time()
runtime = int(endtime-starttime)
sys.stdout.write("The script took %i sec." %runtime)
给出代码的以下部分
更新部分
open("output.asc", "wb")
从filename = sys.argv[2]
更改为使用filename
output.asc
是第二个参数,它将被覆盖(wb
)或附加到(ab
),具体取决于指定的模式李>not in
检查BigTree.asc
读写模式
完整程序
fileobj_out = open(filename, "w")
应该删除问题是
glob
采用的文件名具有完整路径。我做了一些小改动,现在应该可以在你的代码上使用了。例如,不要使用==
,而是使用in
解释
[1]将文件模式从“wb”(写入字节模式)更改为“ab”(追加字节模式),这样,如果文件存在,它将向其追加信息
[2]以这种方式更改了“in”的“==”,如果文件名
f
包含字符串BigTree.asc
,它将跳过此文件并继续请让我知道这是否有帮助
谢谢:D
相关问题 更多 >
编程相关推荐