我正在尝试整理一个文件,该文件接受用户输入他们想要分析的大量文本文件。作为第一步,我想只取他们输入的每个文档的内容(可以是任何数字,没有限制),并将文档的每一行的内容记录为列表中的项目。我想为用户输入的每个文档单独列出一个列表,但这就是我在努力的地方。以下是我到目前为止所做的事情。
def user_input():
prompt = raw_input("Please input the full name (e.g. text_file.txt) or path of a text file:")
global lst
lst = {}
lst[0] = prompt
global file_count
file_count = 1
while len(prompt) > 0:
prompt = raw_input("Please input any additional text files or simply press enter to continue:")
if len(prompt) > 0:
lst[file_count] = prompt
file_count = file_count+1
return lst
def read_in():
for x in lst.values():
file = open(x)
x = file.readlines()
我现在停留在这个部分,因为我不确定如何为每个列表动态分配名称。任何帮助将不胜感激!!
答案 0 :(得分:1)
def get_filenames():
filelist = []
prompts = [
"Please input the full name (e.g. text_file.txt) or path of a text file:",
"Please input any additional text files or simply press enter to continue:"
]
while True:
filename = raw_input(prompts[len(filelist) > 0]).strip()
if not filename:
break
filelist.append(filename)
return filelist
def get_filelines(filelist):
files = {}
for filename in filelist:
with open(filename, 'rb') as fp:
files[filename] = fp.readlines()
return files
if __name__=='__main__':
print get_filelines(get_filenames())