Проблема с написанием кода на Python для удаления байтов из определенной позиции индекса файла

#python #python-3.x

#python #python-3.x

Вопрос:

Я пытаюсь написать простой файл python3, в котором будут перечислены нужные (видимые) файлы в каталоге в файле, затем отредактируйте каждый файл так, чтобы байты в позициях индекса с 5 по 15 были удалены, а измененный файл сохранен в выходной папке.

Я использую следующий файл для сбора имен файлов в выходной файл:

 #!/usr/bin/python 
import os
import sys

path = '.'
print('Filenames and filename length below.')
my_file = open("output_filenames.txt", "w")
my_file.close()
for file in os.listdir(path):
    current_file = os.path.join(path, file)
    print(current_file)
    print(len(current_file) - 2)
    print("""running getFilenames2.py , listing files from the directory once, 
    with clean_string2.py and new_editor.py""")
    x = current_file.strip("./")
    my_file = open("output_filenames.txt", "a")
    my_file.writelines(x)
    my_file.writelines('n')
    my_file.close()
    # this file prints the filenames in the current directory. 
print("This is the end of getFilenames2.py")
 

Затем я хочу удалить лишнюю «. /» часть сгенерированных имен файлов в списке, а также удалить скрытые имена файлов и три файла python, необходимые для всего этого.
В следующем файле я копирую список в новый файл, затем изменяю этот файл, чтобы удалить ненужные имена файлов. Их много, потому что я также пытался заставить это работать, развернув на Pythonanywhere.com , и это имена папок и скрытых файлов или файлов, которые я не хочу перечислять, копировать или изменять при их настройке.
Примерно на полпути вниз по списку файлов для удаления я прокомментировал раздел кода, который иллюстрирует новый способ удаления ненужных файлов, над которым я работаю. Строки с 92 по 108. Должен ли я переключиться на этот формат кода?
Кроме того, я беспокоюсь об удалении данных по ходу работы, поэтому я записываю в совершенно новый файл для запуска и каждый раз, когда я изменяю файл.

 #!/usr/bin/python 
import os
import sys
os.system('python getFilenames2.py')
my_file = open("output_filenames.txt", "r")
file_content = my_file.read()
my_file.close()
x = file_content
my_file = open("output_cleaned_filenames.txt", "a")
my_file.write(x)
my_file.close()
# print(x)
print(type(x))
# remove certain filenames from the list: DS_Store, clean_string.py, output_filenames.txt ,getFilenames.py , 
# output_cleaned_filenames.txt ,output_pruned_filenames.txt, getFilenames.py
# for online use of pythonanywhere website configuration, remove the following filenames:
# virtualenvs, vimrc, local, gitconfig, pythonstartup.py, bashrc, ipython, profile ,output_folder
my_file = open("output_cleaned_filenames.txt", "w")
my_file.write(x)
my_file.close()
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("DS_Store"):
            new_f.write(line)
my_file.close()
# the last seven lines stop DS_Store from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("virtualenvs"):
            new_f.write(line)
my_file.close()
# the last seven lines stop virtualenvs from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("vimrc"):
            new_f.write(line)
my_file.close()
# the last seven lines stop vimrc from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("local"):
            new_f.write(line)
my_file.close()
# the last seven lines stop local from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("gitconfig"):
            new_f.write(line)
my_file.close() 
# the last seven lines stop gitconfig from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("pythonstartup.py"):
            new_f.write(line)
my_file.close() 
# the last seven lines stop pythonstartup.py from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("bashrc"):
            new_f.write(line)
my_file.close() 
# the last seven lines stop bashrc from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("ipython"):
            new_f.write(line)
my_file.close()
# the last seven lines stop ipython from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("profile"):
            new_f.write(line)
my_file.close()
# the last seven lines stop profile from being listed in output_pruned_filenames.txt
# with open("output_cleaned_filenames.txt", "r") as f:
#    lines = f.readlines() 
#with open("output_pruned_filenames.txt", "w") as new_f:
#    pruned_new_f = new_f.strip("output_folder")
#    pruned_new_f.write(new_f)
#   
# infile = "output_pruned_filenames.txt"
# outfile = "cleaned_file.txt"

# delete_list = ["word_1", "word_2", "word_n"]
# with open(infile) as fin, open(outfile, "w ") as fout:
#     for line in fin:
#        for word in delete_list:
#           line = line.replace(word, "")
#        fout.write(line)
# my_file.close()
# the last seven lines stop output_folder from being listed in output_pruned_filenames.txt         
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("clean_string.py"):
            new_f.write(line)
my_file.close()
# the last seven lines stop clean_string.py from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("output_filenames.txt"):
            new_f.write(line)
my_file.close()
# the last seven lines stop output_filenames from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines() 
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("getFilenames.py"):
            new_f.write(line)
my_file.close()
# the last seven lines stop getFilenames.py from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines()
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("output_cleaned_filenames.txt"):
            new_f.write(line)
my_file.close()
# the last seven lines stop output_cleaned_filenames.txt from being listed in output_pruned_filenames.txt
with open("output_cleaned_filenames.txt", "r") as f:
    lines = f.readlines()
with open("output_pruned_filenames.txt", "w") as new_f:
    for line in lines:
        if not line.startswith("output_pruned_filenames.txt"):
            new_f.write(line)
my_file.close()
# the last seven lines stop output_pruned_filenames.txt from being listed in output_pruned_filenames.txt
my_file = open("output_pruned_filenames.txt", "r")
file_content = my_file.read()
my_file.close()
print(file_content)
print("This is the end of clean_string.py")
print('output_pruned_filenames.txt is the final output file')
print('These are the files in the current directory.') 
 

Этот последний файл вызывает наибольшую проблему, это файл, который удаляет некоторые байты из каждого указанного файла при копировании в выходную папку. Байты удаляются из индекса 5 в индекс 14.
Я копирую первые 5 байтов в первый входной файл, затем копирую байты из индекса 15 в конец входного файла и сохраняю их как второй выходной файл.
После этого я объединяю выходные файлы вместе и помещаю в третий выходной файл. Проблема в строке 27. Должен ли я по-прежнему ссылаться на «working_file»?

 # edit_listPytest9.py
import os
os.system('python clean_string2.py')
count = 0
if not os.path.exists('output_folder'):
    os.makedirs('output_folder')
with open("output_pruned_filenames.txt", "rt") as myfile:
    for myline in myfile:
        x = myline.rstrip("n")
        print("n")
        print("This is the filename.")
        count  = 1
        with open(x, "rt") as working_file:
                file_content = working_file.read()
                # print("Here is the content of")
                # print(file_content)
                new_filename = x.rstrip(".txt")
                print(new_filename)
                print(count)
                id = str(count)
                print(new_filename   "_"   id   ".txt")
                # f = file("path/to/file", "w")
                dynamic_filename = new_filename   "_"   id   ".txt"
                print(dynamic_filename)
                with open('output_folder/'   dynamic_filename, 'w') as my_file:
                    my_file.writelines(file_content)
                    my_file = open( working_file, "r")
                    file_content = my_file.read()
                    my_file.close()
                    # print(file_content)
                    print("n"   'This is the length of the input file, '   dynamic_filename   ', it includes spaces and line returns.')
                    print(len(file_content))
                    # print((file_content[0])   (file_content[1])   (file_content[2])   (file_content[3])   (file_content[4])   (file_content[5])   (file_content[6])   (file_content[7])   (file_content[8])   (file_content[9])   (file_content[10])   (file_content[11])   (file_content[12])   (file_content[13])   (file_content[14])   (file_content[15])   (file_content[16])   (file_content[17])   (file_content[18])   (file_content[19])   (file_content[20])   (file_content[21])   (file_content[22])   (file_content[23])   (file_content[24])   (file_content[25])   (file_content[26])   (file_content[27])   (file_content[28])   (file_content[29])   (file_content[30])   (file_content[31])   (file_content[32])   (file_content[33])   (file_content[34])   (file_content[35])   (file_content[36])   (file_content[37])   (file_content[38])   (file_content[39])   (file_content[40]))
                    # print('This is the first 41 characters of 'dynamic_filename '  above.'   'n')
                    # print('n'   'This is the first 10 characters of  'dynamic_filename ' below.'   'n')
                    file_start = ((file_content[0])   (file_content[1])   (file_content[2])   (file_content[3])   (file_content[4])   (file_content[5])   (file_content[6])   (file_content[7])   (file_content[8])   (file_content[9]))
                    # chunk_removed = some number of bytes removed
                    # write back to new file to edit out Chunk
                    # first, strip the .txt extension from dynamic_filename
                    dynamic_filename = dynamic_filename.rstrip(".txt")
                    # this filename will have to be made out of dynamic_filename and indicate purpose: is output_file1.txt originally output_file1 =
                    # dynamic_filename   output_file1.txt
                    my_file = open('output_folder/'   dynamic_filename   "output_file1.txt", "w")
                    # write to output file number 1
                    my_file.writelines(file_start)
                    my_file.close()
                    # output to console or terminal
                    # print(file_start)
                    # print("n"   'This is the length of 'dynamic_filename'output_file1.txt, the first output file.')
                    # print(len(file_start))
                    # file_remaining = my_file.read() # use seek to start read from index [10   chunk_removed]# e.. chunk_removed = 5 characters 10   5 = 15
                    my_file = open(working_file, "r")
                    my_file.seek(15)
                    file_remaining = my_file.read()
                    my_file.close()
                    my_file = open('output_folder/'   dynamic_filename   "output_file2.txt", "w")
                    my_file.writelines(file_remaining)
                    my_file.close()
                    # output_file2.txt starts with the 16th character. Remember that this is the number of characters since index starts at 0.
                    # After 15 characters.
                    # Creating a list of filenames three files - header.txt, output_file1.txt, output_file2.txt
                    filenames = ['header.txt', 'output_folder/'   dynamic_filename   'output_file1.txt', 'output_folder/'   dynamic_filename   'output_file2.txt']
                    # Open output_file3 in write mode to create it and write
                    with open('output_folder/'   dynamic_filename   'output_file3.txt', 'w') as outfile:
                       # Iterate through list
                        for names in filenames:
                           # Open each file in read mode
                            with open(names) as infile:
                                # read the data from  header, file1 and
                                # file2 and write it in file3
                                outfile.write(infile.read())
                                # Add 'n' to enter data of file2 (disabled by comment at the start of this line)
                                # from next line
                                # outfile.write("n")
                                # print(outfile)
                                my_file.close()
                    
 

Комментарии:

1. Почему вы делаете os.path.join(path, file) , а затем удаляете ./ то, что это добавляет? Если вам не нужен префикс каталога, не добавляйте его в первую очередь.

2. writelines() обычно используется со списком или другими повторяющимися строками, содержащими строки. Если вы пишете одну строку, просто используйте write() .

3. Я признаю невежество, я только что изучил Python несколько недель назад, и я просто добавлял фрагменты кода вместе, пока что-то не заработало. Это имеет смысл, что для перечисления файлов в каталоге должен быть просто os.path(file).

4. Приведенный ниже код работает для создания списка имен файлов в каталоге.import os import sys path = ‘.’ print(‘Имена файлов и длина файла ниже.’) my_file = open(«output_filenames.txt «, «w») my_file.close() для файла в os.listdir(путь): current_file = os.path.join(«»,файл) # os.path.join(путь, файл) — это исходный фрагмент кода

Ответ №1:

strip() и rstrip() не предназначены для удаления подстрок. Они удаляют все символы в списке в начале или конце, а не только точную строку. Вы можете использовать re.sub() для удаления подстрок в начале или конце, например

 import re

new_filename = re.sub(r'.txt

Вы делаете запись желаемых байтов намного сложнее, чем это должно быть. Вам не нужны дополнительные файлы, просто разрежьте прочитанную строку.

 with open(x, "r") as working_file:
    file_contents = working_file.read()
# code to calculate dynamic_filename
with open(os.path.join("output_folder", dynamic_filename), "w") as my_file:
    my_file.write(file_contents[0:5]   file_contents[15:])
 

Комментарии:

1. Большое вам спасибо за ваш ответ, я уверен, что это приведет меня к написанию рабочего скрипта на Python для моей цели. Я думаю, что вы хотели сказать, что я должен объединить file_contents[0: 4] и file_contents[15:] , поскольку я "удаляю" десять байтов, начиная с пятого байта. извините, если это было непонятно. Я прав или есть другая деталь, которую я пропустил? Я пропустил крайний случай??

2. Фрагменты не включают второй индекс, поэтому 0:5 означают байты от 0 до 4.

3. Можете ли вы написать то же самое с помощью Pathlib вместо os.path.join ?

4. Я уверен, что вы могли бы.

5. Спасибо, Бармар, я ценю вашу помощь для этого новичка.

, '', filename)
Вы делаете запись желаемых байтов намного сложнее, чем это должно быть. Вам не нужны дополнительные файлы, просто разрежьте прочитанную строку.


Комментарии:

1. Большое вам спасибо за ваш ответ, я уверен, что это приведет меня к написанию рабочего скрипта на Python для моей цели. Я думаю, что вы хотели сказать, что я должен объединить file_contents[0: 4] и file_contents[15:] , поскольку я «удаляю» десять байтов, начиная с пятого байта. извините, если это было непонятно. Я прав или есть другая деталь, которую я пропустил? Я пропустил крайний случай??

2. Фрагменты не включают второй индекс, поэтому 0:5 означают байты от 0 до 4.

3. Можете ли вы написать то же самое с помощью Pathlib вместо os.path.join ?

4. Я уверен, что вы могли бы.

5. Спасибо, Бармар, я ценю вашу помощь для этого новичка.