Как изменить несколько файлов (GJF) в Python - PullRequest
0 голосов
/ 05 декабря 2018

Итак, я пытаюсь изменить содержимое в нескольких файлах, буквы от Cl до F через файл.

Первое, на что следует обратить внимание, - это то, что python не может прочитать входные файлы, которые у меня есть (gjf), поэтому мне нужно сначала преобразовать их в txt файлы.

Я могу выполнить каждый шаг по отдельности, но когда я соединяю все это в один цикл, кажется, что он не работает, может кто-нибудь помочь?

Код:

#import modules
import os

#makes a path to CWD and stored as a string
cwd = str( os.getcwd() )

#finds the root, fodlers and and all the files in the cwd and stores them as 
the variable 'roots' dirs and allfiles
for root, dirs, allfiles in os.walk(r'%s'%(cwd)):
continue

#make a collection of gjf files in the folder
my_files=[]
for i in range(0,len(allfiles),1):
     if allfiles[i].endswith('.gjf'):
         my_files.append(allfiles[i])

 else:continue

#makes all gjf files in txt files

for i in range(0,len(my_files),1):
    base= os.path.splitext(my_files[i]) 
    src=my_files[i]
    os.rename(src, base +'.txt')


#replaces all the Cl ligands with F
for i in range(0,len(my_files),1): 
    s = open("my_files[i]").read()
    s = s.replace('Cl', 'F')
    f = open("my_files[i]", 'w')
    f.write(s)
    f.close()

`

1 Ответ

0 голосов
/ 05 декабря 2018

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

Код:

from glob import glob


# prepare test file
with open('test.gjf', 'w') as f:
    f.write('Cl foo bar ClbarCl')

# print its content
with open('test.gjf', 'r') as f:
    content = f.read()
    print('Before:')
    print(content)

list_of_files = glob('*.gjf')  # get list of all .gjf files

for file in list_of_files:

    # read file:
    with open(file, 'r') as f:
        content = f.read()

    # replace Cl to F:
    new_content = content.replace('Cl', 'F')

    # Write changes:
    with open(file, 'w') as f:
        f.write(new_content)

# Test result
with open('test.gjf', 'r') as f:
    content = f.read()
    print('After:')
    print(content)

Вывод:

Before:
Cl foo bar ClbarCl
After:
F foo bar FbarF
...