You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python遍历目录下txt文件并删除每行首尾的单引号?

需求说明

我在指定目录下存放了多个.txt文件,每个文件中存储了若干被单引号包裹的路径字符串,示例如下:

'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c'
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module2.c'
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module3.c'

需要实现的功能是:遍历该目录下每个文件的每一行,删除每行首尾的单引号,得到纯净的路径,预期效果如下:

C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module2.c
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module3.c
原代码问题

最初编写的代码无法实现需求,代码如下:

for filename in files:
    with open(filename, 'r') as file:
        content = file.read().split('\n')
        for line in content:
            if line.startswith('')and line.endswith(''):
                remove('')

核心问题有两点:

  • startswith('')、endswith('')判断的是空字符串,永远返回True,没有正确匹配首尾的单引号
  • 没有实现有效的单引号移除逻辑,也没有将修改后的内容回写到文件中
可行实现方案

调整思路后可正常运行的实现代码如下:

for filename in files:
    f = open(filename, 'rt')
    filedata = f.read()
    filedata = filedata.replace("'","")
    f.close()
    f = open(filename, 'wt')
    f.write(filedata)
    f.close()

如果需要更严谨的实现(仅删除首尾单引号,避免路径本身中间存在单引号被误删),可以使用优化版本:

import os

# 替换为你的txt文件所在目录路径
dir_path = "你的目标目录路径"
files = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if f.endswith('.txt')]

for filename in files:
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    # 逐行处理,仅删除首尾的单引号
    new_lines = [line.strip().strip("'") + '\n' for line in lines if line.strip()]
    with open(filename, 'w', encoding='utf-8') as f:
        f.writelines(new_lines)

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 22:06:02