栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用python替换特定行中的字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用python替换特定行中的字符串

一些注意事项:

  1. string.replace
    并且
    re.sub
    不在位,因此您应该将返回值分配回变量。
  2. glob.glob
    更好地在目录中查找与已定义模式匹配的文件…
  3. 也许您应该在创建目录之前检查该目录是否已经存在(我只是假设这样做,这可能不是您想要的行为)
  4. with
    语句负责以安全的方式关闭文件。如果您不想使用它,则必须使用
    try
    finally
  5. 在您的示例中,您忘记放置sufix
    *.clean
    ;)
  6. 您在没有实际写入文件的地方,可以像我在示例中所做的那样使用
    fileinput
    模块或使用模块(直到今天我还不知道)

这是我的例子:

import reimport osimport globsource_dir=os.getcwd()target_dir="clean"source_files = [fname for fname in glob.glob(os.path.join(source_dir,"*.seq"))]# check if target directory exists... if not, create it.if not os.path.exists(target_dir):    os.makedirs(target_dir)for source_file in source_files:   target_file = os.path.join(target_dir,os.path.basename(source_file)+".clean")   with open(source_file,'r') as sfile:      with open(target_file,'w') as tfile:         lines = sfile.readlines()         # do the replacement in the second line.         # (remember that arrays are zero indexed)         lines[1]=re.sub("K|Y|W|M|R|S",'N',lines[1])         tfile.writelines(lines)print "DONE"

希望能帮助到你。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/626301.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号