Question

Python, I need help with glob. I have a lot of data text files and want...

Python, I need help with glob. I have a lot of data text files and want to order them. However glob makes it in the wrong order.

Have:

data00120.txt

data00022.txt

data00045.txt

etc

Want:

data00000.txt

data00001.txt

data00002.txt

etc

Code piece:

def last_9chars(x):

    return(x[-9:])

files = sorted(glob.glob('data*.txt'),key = last_9chars)

whole code:

import numpy as np

import matplotlib.pyplot as plt

import glob

import sys

import re

from prettytable import PrettyTable

def last_9chars(x):

    return(x[-9:])

files = sorted(glob.glob('data*.txt'),key = last_9chars)

x = PrettyTable()

x.field_names = ['DataNum', 'Mean', 'Standard Deviation']

filecount = 0

n = 0

maxfilecount = int(sys.argv[1]) if len(sys.argv) > 1 else len(files)

for f in files:

    filecount +=1

    my_data = np.loadtxt(f, delimiter='\t')

    mean = np.mean(my_data[1])

    std = np.std(my_data[1])

    

    print(f"Here {n}")

    x.add_row([f"{f}", mean, std])

    n +=1

    if filecount >= maxfilecount:

        break

print(x)

data = x.get_string()

with open('Data.csv', 'w') as f:

    f.write(data)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

i am using python 3.7 and code for the above is : -

 import numpy as np import matplotlib.pyplot as plt import glob import sys import re from prettytable import PrettyTable # function to extract last 9 characters of the filename def last_9chars(x): return(x[-9:]) # files stores the filenames grabbed by glob module matching to data* in sorted order # glob returns a list of names of files files = sorted(glob.glob('data*.txt'),key = last_9chars) # pretty tables is used for generating tables in python x = PrettyTable() x.field_names = ['DataNum', 'Mean', 'Standard Deviation'] filecount = 0 n = 0 maxfilecount = int(sys.argv[1]) if len(sys.argv) > 1 else len(files) # iterating over list of file names for f in files: filecount +=1 # m_data stores the contents of the text files my_data = np.loadtxt(f, delimiter='\t') # numpy method to find the mean of the data mean = np.mean(my_data[1]) # numpy method to find the standard deviation of data std = np.std(my_data[1]) # add new low in table x.add_row([f"{f}", mean, std]) n +=1 if filecount >= maxfilecount: break print(x) data = x.get_string() # create a new file named Data.csv and write into that with open('Data.csv', 'w') as f: f.write(data)

input files :-

output is :-

if my answer helped then please upvote and comment for any queries

thankyou !

Add a comment
Know the answer?
Add Answer to:
Python, I need help with glob. I have a lot of data text files and want...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • Python, given a code in class i just need help with the third bullet point ; using a and n (defin...

    Python, given a code in class i just need help with the third bullet point ; using a and n (defined in the second picture of python code) find the first digit for k! for k =1,...,n. you dont have to type in all this code just help me write the code in the first picture where it says: def benford(a): b = [0 for d in range(1,10)] #Do everthything in here return b 2.2 Generating data In this assignment...

  • I need help with the following When you run it like the following: python3 decorator.py CrocodileLikesStrawberries...

    I need help with the following When you run it like the following: python3 decorator.py CrocodileLikesStrawberries The token "CrocodileLikesStrawberries" allows you to interact with the functions. This code is OK, but there is repetition with the checks for auth_token. We could pull this out into it's own function, but what is even better design is to use a decorator. Create an authorise decorator and use it with the refactored code given below. import sys MESSAGE_LIST = [] @authorise def get_messages():...

  • PLEASE HELP ASAP! in Python, I am supposed to create a program that compares insertion sorting...

    PLEASE HELP ASAP! in Python, I am supposed to create a program that compares insertion sorting and selection sorting. My program only compares insertion and selection once. It is supposed to compare increasing, decreasing and an array of random values for each at 5 different lengths (without looping). Please help me. I have included my code below. import time import random def insertion_sort(arr):     for i in range(1, len(arr)):         key = arr[i]         j = i - 1         while j >= 0...

  • Please help! I am trying to make a convolution but i am receiving a syntax error....

    Please help! I am trying to make a convolution but i am receiving a syntax error. If anyone can help with how to do the convolution it would be much appreciated! This first part is the main program. import numpy as np from numpy import * import pylab as pl import wave import struct from my_conv import myconv #import scipy.signal as signal ##-------------------------------------------------------------------- ## read the input wave file "speech.wav" f = wave.open("speech.wav", "rb") params = f.getparams() nchannels, sampwidth, framerate,...

  • I need help writing python code with following instructions. You will write a program that reads...

    I need help writing python code with following instructions. You will write a program that reads a data file. The data file contains ticket IDs and ticket prices. Your job is to read these tickets (and prices). find minimum, maximum and average ticket prices and output a report file. The report file should look exactly (or better than) the one attached (output.txt). Input: A31 149.99 B31 49.99 A41 179.99 F31 169.99 A35 179.99 A44 169.99 open "input.txt" file using open()...

  • Hi. It's a python and I got an error below comment import numpy as np arr=np.genfromtxt("/Volumes/Samsung...

    Hi. It's a python and I got an error below comment import numpy as np arr=np.genfromtxt("/Volumes/Samsung SSD 860 EVO 500GB Media/Download/primenumbers.txt", dtype=int) arr=arr.reshape(-1,1) arr.shape def find_cat(x): if x<= 300: return '<=300' elif x <= 600: return '<=600' else: return '<=1000' arr2 = np.apply_along_axis(find_cat, axis=1, arr=arr) arr2 = arr2.reshape(-1,1) arr3 = np.hstack((arr, arr2)) arr_300 = np.array((col[0] for col in arr3 if col[i]=='<=300'), dtype=int) arr_300 arr_300.shape count_300=len(arr_300) count_300 avg_300=round(np.mean(arr_300, 2) avg_300 print("Number of items in category \ "<=300\"= (one), and average of...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • I need python help .. I need to know if a user were to input 3...

    I need python help .. I need to know if a user were to input 3 commands to a program and run it such as specify: Usage: ./filemaker INPUTCOMMANDFILE OUTPUTFILE RECORDCOUNT (./filemaker is the program)( (INPUTCOOMANDFUILE= a text file that contains key words that need to be searched through then decided what to do ) (RECORDCOUNT= number) Given an input file that contains the following: That specifies the text, then the output, and the number of times to be repeated...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT