Python 将文件下载到内存中
我正在编写一个python脚本,我只需要一系列非常小的文本文件的第二行。我想在不将文件保存到硬盘驱动器的情况下提取此文件,就像我目前所做的那样 我发现了一些引用TempFile和StringIO模块的线程,但我无法理解它们 目前我下载了所有的文件,并按顺序命名为1.txt、2.txt等,然后遍历所有文件并提取第二行。我想打开文件,抓住这一行,然后继续查找、打开和阅读下一个文件 以下是我目前将其写入硬盘的做法:Python 将文件下载到内存中,python,temporary-files,stringio,Python,Temporary Files,Stringio,我正在编写一个python脚本,我只需要一系列非常小的文本文件的第二行。我想在不将文件保存到硬盘驱动器的情况下提取此文件,就像我目前所做的那样 我发现了一些引用TempFile和StringIO模块的线程,但我无法理解它们 目前我下载了所有的文件,并按顺序命名为1.txt、2.txt等,然后遍历所有文件并提取第二行。我想打开文件,抓住这一行,然后继续查找、打开和阅读下一个文件 以下是我目前将其写入硬盘的做法: while (count4 <= num_files): file_p
while (count4 <= num_files):
file_p = [directory,str(count4),'.txt']
file_path = ''.join(file_p)
cand_summary = string.strip(linecache.getline(file_path, 2))
linkFile = open('Summary.txt', 'a')
linkFile.write(cand_summary)
linkFile.write("\n")
count4 = count4 + 1
linkFile.close()
while(count4在每次迭代中打开和关闭输出文件
为什么不干脆做呢
with open("Summary.txt", "w") as linkfile:
while (count4 <= num_files):
file_p = [directory,str(count4),'.txt']
file_path = ''.join(file_p)
cand_summary = linecache.getline(file_path, 2).strip() # string module is deprecated
linkFile.write(cand_summary)
linkFile.write("\n")
count4 = count4 + 1
此外,如果您删除strip()
方法,则不必重新添加\n
,但谁知道为什么会在其中添加它。也许.lstrip()
会更好
最后,手动while循环是什么?为什么不使用for循环呢
最后,在你的评论之后,我知道你想把结果放在一个列表而不是一个文件中。好的
总而言之:
summary = []
for count in xrange(num_files):
file_p = [directory,str(count),'.txt'] # or count+1, if you start at 1
file_path = ''.join(file_p)
with open(file_path, "r") as infile:
dummy = infile.readline()
cand_summary = infile.readline().strip()
summary.append(cand_summary)
只需在列表中调用append()
,即可替换文件写入。例如:
summary = []
while (count4 <= num_files):
file_p = [directory,str(count4),'.txt']
file_path = ''.join(file_p)
cand_summary = string.strip(linecache.getline(file_path, 2))
summary.append(cand_summary)
count4 = count4 + 1
summary=[]
虽然(count4)我想问题是“我如何在不写summary.txt的情况下将摘要保存在内存中”我必须承认我根本不确定问题是什么。标题是关于“下载”,但代码中根本没有下载…下载部分在脚本的另一部分,但David是正确的,很抱歉没有更好地解释它。有一个网站提供了一个文件供下载,我宁愿不下载文件,然后打开它,然后抓取第二行,我想知道是否有更直接的方法se用于范围内的count4(1,num_files+1)
而不是自己递增!@agf同意,但我不能100%确定count4从1开始运行。我对您学习Python所用的教程/书籍非常感兴趣,因此我可以向您推荐一本不同的教程/书籍。
summary = []
while (count4 <= num_files):
file_p = [directory,str(count4),'.txt']
file_path = ''.join(file_p)
cand_summary = string.strip(linecache.getline(file_path, 2))
summary.append(cand_summary)
count4 = count4 + 1