从文本文件中读取文件路径并修改每个路径

2024-09-30 12:32:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件(文件名.txt)其中包含200多个文件路径:

/home/chethan/purpose1/script1.txt
/home/chethan/purpose2/script2.txt
/home/chethan/purpose3/script3.txt
/home/chethan/purpose4/script4.txt

在这些文件中的多行中,每一行都包含一行文件名,如Reference.txt。我的目标是在中替换.txt参考.txt在每个文件中都有.csv。作为Python的初学者,我参考了stackoverflow中关于类似情况的几个问题,并编写了以下代码。在

我的代码:

^{pr2}$

当我运行我的代码时,上面提到的txt文件(script1,script2….)的内容会被清除,也就是说,它们里面不会有一行文本!我对这种行为感到困惑,无法找到解决办法。在


Tags: 文件代码路径txthome文件名文本文件script2
1条回答
网友
1楼 · 发布于 2024-09-30 12:32:59

这应该能让你继续(未经测试):

#! /usr/bin/python
#filename modify_hob.py

# Open the file with filenames list.
with open('filenames.txt') as list_f:

    # Iterate over the lines, each line represents a file name.
    for filename in list_f:

        # Rewrite its content.
        with open(filename) as f:
            content = f.read()
        with open(filename, 'w') as f:
            f.write(content.replace('.txt', '.csv'))

在下面的代码中,f被设置为filename.txt的打开文件对象,并且 没别的了。这就是你在最后两行的结尾。在

而且,您没有将任何内容写回文件中,因此您不能期望 要写回磁盘的更改。(除非fileinput模块做了一些 我不知道的黑暗魔法。)

相关问题 更多 >

    热门问题