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! 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,...

  • 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,...

  • Hey I have a task which consists of two part. Part A asks for writing a...

    Hey I have a task which consists of two part. Part A asks for writing a program of WORD & LINE CONCORDANCE APPLICATION in python which I have completed it. Now the second part has given 5 dictionary implementation codes namely as: (ChainingDict, OpenAddrHashDict with linear probing, OpenAddrHashDict with quadratic probing, and 2 tree-based dictionaries from lab 12 (BST-based dictionary implementation) and asks for my above program WORD & LINE CONCORDANCE APPLICATION  to use these implemented code and show the time...

  • 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...

  • Project Description Allow the user to specify M (the size of the hash table) then, (1)...

    Project Description Allow the user to specify M (the size of the hash table) then, (1) add items found in text file "Project1.txt" to h, an initially-empty instance of a HASH (reject all items that have a key that duplicates the key of a previously added item—item keys must be unique); (2) display h (see format shown below); (3) delete 4 randomly-chosen items from the h; and finally, (4) display h. Note M must be a prime number, so your...

  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

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
ADVERTISEMENT