当前位置: 代码迷 >> python >> 将列表中的值转换为 Python 中的文件名
  详细解决方案

将列表中的值转换为 Python 中的文件名

热度:42   发布时间:2023-06-13 17:25:09.0

如果我有一个文件,例如在一行中包含“foo bar”,我如何将该文件转换为一个列表,以便我可以从中打开 foo 文件和 bar 文件?

编辑:如果我有一个名为“filenames”的文件,其中包含内容“foo bar”,我将如何从创建列表到打开 foo 文件、编辑其内容并将它们写入 bar 文件? 这是我到目前为止所得到的。

import re

def main():   
    file = open('filenames.txt', 'r')
    text = file.read().lower()
    file.close()
    text = re.sub('[^a-z\ \']+', " ", text)
    words = list(text.split())

main()

这是一种方法来做到这一点......

lst = list()
with open(myfile) as f:
    for line in f:
        lst.extend(line.split(" "))  # assuming words in line are split by single space
print lst  # or whatever you want to do with this list

打开名为"filenames" ,读取第一行并获取要读取的source文件和要写入的target文件的名称:

with open("filenames", 'r') as f:
        # Read contents on file:
        text = f.readline()
        source = text.split(" ")[0]
        target = text.split(" ")[1]

现在,使用以下代码,您可以读取源文件、执行操作并将其写入目标文件:

with open(source, 'r') as s:
        # Read contents on file:
        source_text = s.read()

        # Do stuff with source text here

        # Now, let's write it to the target file:
        with open(target, 'w') as t:
            t.write('stuff to write goes here')

就这样。

有关读取和写入文件的更多信息,请阅读。