编辑具有相同名称的文件

时间:2019-03-04 09:12:59

标签: python python-3.x

名称相同的文件,例如

File.txt
File(2).txt
File(3).txt
File(4).txt

以此类推。我该怎么做,无论我在同一目录中放入多少同名文件,它们都将由我的脚本进行编辑? 使Python成为现实的东西File(Some number here).txt并编辑它们,无论显示多少数字?

新的解释

param = 'ORIGINAL PARAMS/PARAM.SFO'
with open (param, 'rb') as p, open('PATCHED PARAMS/PARAM.SFO', 'wb') as o:
        o.write(p.read().replace(b'\x85', b'\xA5'))

我希望它以如上所述的相同名称打开目录'ORIGINAL PARAMS'中的文件。然后,应对其进行编辑,然后将它们输出到具有相同名称但{x85字节已更改为xA5的'PATCHED PARAMS'

@BoboDarph,您的代码对我也不起作用。

1 个答案:

答案 0 :(得分:0)

浏览完注释部分后,我认为我可能有解决OP问题的方法。像往常一样,问题似乎是X对Y的问题,OP要求提供某些东西,但期望得到其他回报。

因此,根据OP的评论,这是一种可能的实现方式。

import os
import inspect


# Assuming you have a project with the following tree structure:
''''<current_dir>
     my_script.py
     ORIGINAL PARAMS
         PARAM.SFO
     ...
     PATCHED PARAMS
         notPARAM.SFO
         PARAM.SFO
         PARAM(1).SFO
         PARAM(2).SFO
         ...
'''''
# The following script will list the contents of PATCHED PARAMS, filter all files that start with PARAM, then for each
# open the source_filename, read it, replace all \x85 binary characters with \xA5 characters in the bytestream
# and write the resulting bytestream to the previously opened PARAM* file.
# Do note that opening a file with wb will either create it if it does not exist, or completely overwrite it
# In order to avoid problems with relative paths, we get the current directory of the script
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# Knowing the relative structure of our project, we could always assume that the target of our script is in the
# same PATCHED PARAMS folder, so we save that path as another script variable
patched_params_directory = 'PATCHED PARAMS'
patched_params = os.path.join(currentdir, patched_params_directory)
# This would be the initial source file that contains the values (the one you read and get the value to replace)
original_directory = 'ORIGINAL PARAMS'
original_filename = 'PARAM.SFO'
# And this would be it's full path. This is here to avoid issues with relative paths
source_filename = os.path.join(currentdir, os.path.join(original_directory, original_filename))
# This is the prefix of all the files we want to alter
params_file_prefix = 'PARAM'
# For every file in the contents of the PATCHED PARAMS directory that starts with PARAM
# So for example PARAM(1) would be accepted, while 1PARAM would not
# param or PaRaM would also not be accepted. If you want those to be accepted, cast both filenames and prefix to lower
for file in [_ for _ in os.listdir(patched_params) if _.startswith(params_file_prefix)]:
    # Calculate the destination filename based on our filter
    dest_filename = os.path.join(patched_params, file)
    # Open both source and dest files, parse the source, write changes to dest
    with open(dest_filename, 'wb') as f, open(source_filename, 'rb') as p:
        f.write(p.read().replace(b'\x85', b'\xA5'))