简体   繁体   English

为多个文件运行相同的代码 Python

[英]Run the Same Code for Multiple Files Python


I've written a code as you can see (I know it could have written better).如您所见,我已经编写了代码(我知道它可以写得更好)。 So my question is how can I run this code for multiple files in a folder?.所以我的问题是如何为文件夹中的多个文件运行此代码? Can I use "for loop" for this?我可以为此使用“for循环”吗?
My files are in a folder called task1 and to be honest I couldn't figure out the way to do it.我的文件在一个名为task1的文件夹中,老实说我不知道​​怎么做。 Thank you for spending your time to read it.感谢您花时间阅读它。

bands = list()

filename = "file1000"
with open (filename) as fin:
    for line in fin:
        bands.append(line.strip())


def partition(bands, start, end):
    pivot = bands[start]
    low = start + 1
    high = end

    while True:
        while low <= high and bands[high] >= pivot:
            high = high - 1
        while low <= high and bands[low] <= pivot:
            low = low + 1
        if low <= high:
            bands[low], bands[high] = bands[high], bands[low]
        else:
            break

    bands[start], bands[high] = bands[high], bands[start]

    return high

def quick_sort(array, start, end):
    if start >= end:
        return

    p = partition(array, start, end)
    quick_sort(array, start, p-1)
    quick_sort(array, p+1, end)


def heapify(bands, n, i):
    largest = i
    l = 2 * i + 1
    r = 2 * i + 2

    if l < n and bands[i] < bands[l]:
        largest = l

    if r < n and bands[largest] < bands[r]:
        largest = r

    if largest != i:
        bands[i], bands[largest] = bands[largest], bands[i]
        heapify(bands, n, largest)

def heapSort(bands):
    n = len(bands)


    for i in range(n, -1, -1):
        heapify(bands, n, i)


    for i in range(n - 1, 0, -1):
        bands[i], bands[0] = bands[0], bands[i]
        heapify(bands, i, 0)


def mergeSort(bands):
    if len(bands) > 1:
        mid = len(bands) // 2
        L = bands[:mid]
        R = bands[mid:]

        mergeSort(L)
        mergeSort(R)

        i = j = k = 0

        while i < len(L) and j < len(R):
            if L[i] < R[j]:
                bands[k] = L[i]
                i += 1
            else:
                bands[k] = R[j]
                j += 1
            k += 1

        while i < len(L):
            bands[k] = L[i]
            i += 1
            k += 1

        while j < len(R):
            bands[k] = R[j]
            j += 1
            k += 1


def insertionSort(bands):
    for i in range(1, len(bands)):

        key = bands[i]

        j = i - 1
        while j >= 0 and key < bands[j]:
            bands[j + 1] = bands[j]
            j -= 1
        bands[j + 1] = key

import time
start_time = time.time()
quick_sort(bands, 0, len(bands) - 1)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write("        ")
file.close()

start_time = time.time()
heapSort(bands)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write("        ")
file.close()

start_time = time.time()
mergeSort(bands)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write("        ")
file.close()

start_time = time.time()
insertionSort(bands)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write("        ")
file.close()

You can use:您可以使用:

d="**Provide the directory here**"
files=os.listdir(d)
file=[i[:-4] for i in files]          #To store the csv file name as DataFrame name without the '.csv' part
a=[]
for i in range(len(files)):
    exec("%s=pd.read_csv(d+files[i])"%file[i])
    a.append(file[i])

Now you the list of DataFrames in 'a'.现在您是“a”中的 DataFrame 列表。 You can iterate for each of them and pass it to your function.您可以迭代它们中的每一个并将其传递给您的函数。

You can use os.listdir(folder) to get all names in folder (it will be names of files and subfolders) and then you can use for -loop to run your code with every filename.您可以使用os.listdir(folder)获取os.listdir(folder)所有名称(它将是文件和子文件夹的名称),然后您可以使用for -loop 使用每个文件名运行您的代码。 listdir() gives only filenames and you need os.path.join() to create full path to file. listdir()仅提供文件名,您需要os.path.join()来创建文件的完整路径。 You can also use if to filter names.您还可以使用if来过滤名称。

import os

folder = "/path/to/assignment"

for name in os.listdir(folder): 
    if name.startswith("file"): # use it if you have to filter files by name
        filename = os.path.join(folder, name)
        print(filename)

        # ... your code ...

Eventually you can use glob for this.最终,您可以为此使用glob It can be useful if you wan to filter names.如果您想过滤名称,它会很有用。 For all names use * .对于所有名称,请使用* To filer you can use ie *.txt or file* , etc.对于文件管理器,您可以使用 ie *.txtfile*等。

import glob

#for filename in glob.glob("/path/to/assignment/file*.txt"):
for filename in glob.glob("/path/to/assignment/*"):
     print(filename)

     # ... your code ...

If you will need to get also in subfolders then you can use os.walk(folder)如果您还需要进入子文件夹,则可以使用os.walk(folder)

import os

folder = "/path/to/assignment"

for root, dirs, files in os.walk(folder):
     for name in files:
         if name.startswith("file"): # use it if you have to filter files by name
             filename = os.path.join(root, name)
             print(filename)

             # ... your code ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM