Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I need Help with my code
#1
Hello guys, i have this simple code. its taking tree random rows from a Excel and printing it out into a txt document.
its working well but i should do the same process with 30 excel and every time i have to choose the file... also i need to execute this code on more excel files... is there a way to automate it? like a loop or something...
from tkinter import filedialog
import tkinter
import pandas as pd
import numpy as np
import sys
from datetime import datetime

from pandas.core.indexes.base import Index
from tkinter import Tk    
from tkinter.filedialog import askopenfilename

Tk().withdraw() 
filename = askopenfilename() 



df = pd.read_excel(filename)
df_new= [df.drop(columns =["note"], inplace=True),
df.sample(n=3)]


filename1 = datetime.now().strftime("%Y%m%d")
sys.stdout = open(filename1 + '.txt', 'w')
print(df_new)
sys.stdout.close()
Reply
#2
If the files are all in the same directory you could use os.listdir to read filenames.

import os

dir_contents = os.listdir('c:/dev/test')

for item in dir_contents:
    if item.endswith('.xls'):
        # do something to this file
        print(item)
Reply
#3
Yes. How easy it is depends on the similarities in the filenames.
At 13, rather than calling askopenfilename() you would start your loop. I suggest you start there by creating a list of the filenames then having a for loop that iterates over those filenames (for filename in list_of_names:)
Fannel likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020