将多个txt文件中的行读入变量

时间:2018-11-05 08:07:33

标签: python

我在一个目录中有多个txt文件,其中每个txt文件都有几行哈希:

546516fdsfgbfdgbfdf

232321dfsfdsgfdgvfd

321656fdsfsffgfdgfd

我正在尝试读取目录中所有txt文件中的每一行,然后将它们传递给“ 哈希”变量,并每次重新运行脚本以下载哈希二进制文件文件。

import requests

f = open('*.txt')
    hash = f.read().splitlines()
    f.close()

    params = {'apikey': 'XXXXXXXXXXXXXX', 'file': (hash)}
response = requests.get('https://www.test.com/file/download', params=params)

downloaded_file = response.content

if response.status_code == 200:
    with open('/tmp/sample.bin', 'wb') as f:
        f.write(response.content)

3 个答案:

答案 0 :(得分:0)

如果您试图将整行读入num,那将达到目的。

if response.status_code == 200:
    with open('/tmp/file.bin', 'wb') as f:
        num = f.read()

答案 1 :(得分:0)

有类似的问题,如果出现,我需要在文件夹的每个文件中更改某个字符串。

重要。这是一个相当老的脚本,因此有一些事情要做。我建议解决这些问题,以提高代码质量:

  • 如果发生错误,请尝试加注阻止。
  • 定义正则表达式对象而不是在行中定义它们,算法与此配合使用会更快
  • 应用列表推导

注意:我使用regex101.com创建正则表达式。

import os, fnmatch, re

allLinesString = []

def findReplace(directory, filePattern):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, filePattern):
            filepath = os.path.join(path, filename)
            global i
                with open(filepath, "r") as f:
                    for line in f:
                    # So lets decide here what to do when we go through each line of each file found in the directory
                        if "String" in line:
                            # Okay and here we write the String if "String" is in line to an array
                            allLinesString.append(line)
                            # And if you want you can even use a regex expression to manipulate the "String" which you just found, or delete certain characters what so ever
                            # Or write the entry to a varible called num in your case
                            allLinesString[i] = re.sub(r'^\s', '', allLinesString[i])

# In this case the function searches for all markdown files for the specific string
if __name__ == '__main__':
    findReplace("wantedDirectoryPath/", "*.md")

答案 2 :(得分:0)

据我了解,阅读所有哈希将解决您的问题。尝试一下,然后看看评论。

import os
import requests

# If text files aren't in the same dir, edit path as you see fit
path = os.getcwd()

# Reads all text files in current directory.
all_files = [i for i in os.listdir(path) if i[-4:] == '.txt']
all_hashes = []

for file in all_files:
    with open(path+file,'r+') as f:
        lines = f.readlines()
    for line in lines:
        # Handling empty lines only here, add regex or more params to strip if needed
        if not line.strip('\n'):
            continue
        # All hashes are now stored in a list
        all_hashes.append(line.strip('\n'))

# Just iterate over the list and make requests
# You may want to add a delay with time.sleep() in the loop
for hash in all_hashes:
    params = {'apikey': 'XXXXXXXXXXXXXX', 'file': (hash)}
    response = requests.get('https://www.test.com/file/download', params=params)
    downloaded_file = response.content

    if response.status_code == 200:
        # you may want to use 'a' instead of 'wb' here?
        with open('/tmp/sample.bin', 'wb') as f:
            f.write(response.content)

编辑:另请参阅this帖子,该帖子告诉您如何从目录中读取所有txt文件,而在this处显示如何读取文件,一行一行地进入列表。