麻烦万能的python王帮忙编个小程!感激不尽!【在线等】
发布网友
发布时间:2023-07-17 11:40
我来回答
共5个回答
热心网友
时间:2024-12-06 05:50
#coding=utf-8
'''
Created on 2014-11-10
@author: Neo
'''
import os
def GetFileList(dir, fileList, nameList):
#文件列表fileList
#只取文件名的列表nameList
newDir = dir
if os.path.isfile(dir):
fileList.append(dir.decode('gbk'))
nameList.append(os.path.basename(dir.decode('gbk')))
elif os.path.isdir(dir):
for s in os.listdir(dir):
if s == ".popoCloud":
continue
newDir=os.path.join(dir,s)
GetFileList(newDir, fileList, nameList)
return fileList, nameList
fileList = []
nameList = []
#你存放fas文件的目录,如:
#dir = 'd:/xxx/xxx/'
dir = (os.getcwd() + '\\fas\\').replace('\\','/')
fileList, nameList = GetFileList(dir, fileList, nameList)
print fileList, nameList
#根据你的要求替换文件内容
for i in range(fileList.__len__()):
print fileList[i]
fp = open(fileList[i],'r')
#我不清楚你的每个fas有多大,如果比较大,就换一种读写方式
str = fp.read()
fp.close()
# print str
str = str.replace('>', '>' + nameList[i][:-4] +'_')
# print str
fp = open(fileList[i],'w')
fp.write(str)
fp.close()
print "OK"
效果如下:
[u'D:/workspace/PyDemo/fas/AAAA.fas', u'D:/workspace/PyDemo/fas/BBBB.fas', u'D:/workspace/PyDemo/fas/CCCC.fas'] [u'AAAA.fas', u'BBBB.fas', u'CCCC.fas']
D:/workspace/PyDemo/fas/AAAA.fas
D:/workspace/PyDemo/fas/BBBB.fas
D:/workspace/PyDemo/fas/CCCC.fas
OK
热心网友
时间:2024-12-06 05:50
看下面的代码,用函数 update_files('/path/to/fas/files') 可以将 /path/to/fas/files 目录下的所有 xxx.fas 文件做你需要的修改。 (使用前注意备份,它会直接修改文件)
import os
def update_files(path):
for f in os.listdir(path):
if not os.path.isfile(f):
continue
name, sep, suffix = os.path.basename(f).rpartition('.')
if sep != '.' or suffix != 'fas':
continue
with open(f, 'r') as fd:
text = fd.read()
with open(f, 'w') as fd:
lines = ['>%s_%s' % (name, l[1:]) if l[0] == '>' else l
for l in text.splitlines(True)]
fd.writelines(lines)
# update_files('/path/to')
# update_files('.')
热心网友
时间:2024-12-06 05:51
如果只是这样的话,很简单的:
from glob import glob
for re_filename in glob("*.fas"):
input_file = open(re_filename).read()
new_file = open('new_'+re_filename,'w').write(input_file.replace('>','>'+re_filename[:-4]+'_'))
new_file.close()
热心网友
时间:2024-12-06 05:52
import os.path
def lineadjust(ln, fname):
return ln.startswith(">") and (">%s_%s" % (fname, ln[1:])) or ln
def filecontextadjustbyname(fullname):
fname, ename = os.path.splitext(os.path.basename(fullname))
context = [lineadjust(ln, fname) for ln in open(fullname)]
with open(fullname, 'wt') as handle:
handle.writelines(context)
for filename in yourfilelist:
context = filecontextadjustbyname(filename)
热心网友
时间:2024-12-06 05:52
文件内容多不多?