如果我有一个包含例如" foo bar"的文件在一行中,我怎么能将该文件转换为列表,以便我可以从中打开foo文件和bar文件?
编辑: 如果我有一个名为' filenames'包含内容' foo bar',如何从创建列表到打开foo文件,编辑其内容并将其写入条形文件?这是我到目前为止所做的。
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()
答案 0 :(得分:0)
这是一种方法......
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
答案 1 :(得分:0)
打开名为"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')
这就是全部。
有关读取和写入文件的更多信息,请阅读docs。