Skip to main content
 首页 » 编程设计

python之如何在 python 中更改多个文件 (gjf)

2024年12月31日6lyj

所以我试图更改多个文件中的内容,从文件中的字母 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() 

`

请您参考如下方法:

您不需要将其转换为 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