How can I pass a excel/csv file as a function parameter? - python-3.x

How can I pass a excel/csv file as a function parameter?
I have wrote a piece of code to copy content from one excel file to another excel file. Now I want to define it as a function so I just have to mention file name from which I want to transfer data to my existing file.
Thanks a lot in advance.
I am very new to Python Programming, and looking forward to learn a lot.
def feed_input_file(InputFile):
InputFile = "D:\\Python_Projects\\ABC.xlsx" #(I am passing Input file at the moment but I don't wanna pass it here)
#( Here I am trying to call my function parameter value)
Workbook1 = xl.load_workbook(feed_input_file(InputFile))
............

Still not quite sure what you are trying to do but if you want to create a function that will take a filename as an argument you could try something along the lines of:
def processFile(fn:str):
#Reads in the contents of file specified by fn
content = ''
with open(fn, 'a') as f:
data = f.read()
#Do something with data here to create content
return content
Then in your main part of the script
for filename in listofFiles:
fle_out = processFile(filename
#Do something here with file contents

Related

How do I dynamically create a variable name in a loop to assign to a file name in python 3

I'm still relatively new to programming and Python. But I am sure this must be possible but my searches are not turning up what I'm looking for.
In my current directory, I have 6 PDF files that I wish to read in via the loop below.
What I would like to do is open each of the PDF's with a new variable name, as you can see it is imaginatively called pdf[1-6]File.pdf.
I can list the files in the console and pull them via the code when I stick breaks in to stop it executing but I can't for the life of me work out how to create the variable name. I thought something like "pdf" + str(i) + "File" would have worked but I'm missing something.
Code is below - not complete but enough so you get what I'm looking at:
#Open the PDF files in the current directory for
#reading in binary mode
def opensource():
listOfFiles = os.listdir('.')
pattern = "*.pdf"
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
# Works to here perfectly
for i in range(len(entry)):
# print(len(entry))
# Trying to create the variable name with
# an incremental numeral in the file name
"pdf" + i + "File" = open(entry, 'rb')
This bit below is how I'm currently doing it and its a pain in the backside. I'm sure it can be done programmatically
#This is the old way. Monolithic and horrid
#Open the files that have to be merged one by one
pdf1File = open('file1.pdf', 'rb')
pdf2File = open('file2.pdf', 'rb')
pdf3File = open('file3.pdf', 'rb')
pdf4File = open('file4.pdf', 'rb')
pdf5File = open('file5.pdf', 'rb')
pdf6File = open('file6.pdf', 'rb')
All help gratefully received.
Thanks
If you are going to use the file pointer outside this for loop, you can very well use a dictionary to do that..
def opensource():
listOfFiles = os.listdir('.')
pattern = "*.pdf"
file_ptrs = {}
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
# Works to here perfectly
for i in range(len(entry)):
# print(len(entry))
# Trying to create the variable name with
# an incremental numeral in the file name
file_ptrs["pdf" + str(i) + "File"] = open(entry, 'rb')
Caution: Its always advisable to use the open method alongside of a "with" clause in python.. it takes care of closing the file once the file operation goes out of context.

looping through a file with python

New to python and stuck on reading a file...
I want to search a file for data using python3.
I have a data file that looks like this:
hostname,timestamp,#of CPUs,memory,cpu,disk
hostname1,07311906,1,4.84%,74%,0.45%
hostname2,07311906,2,3.84%,24%,0.45%
hostname1,07311907,1,4.85%,74%,0.49%
hostname2,07311907,2,4.64%,44%,0.30%
hostname1,07311908,1,5.20%,74%,0.78%
hostname2,07311908,2,4.44%,54%,0.40%
I'd like to cycle through a config file like this pseudo code:
for i in server.list do
<graph the data server i for the month of `date %m`>
done
The end goal is loop through my data file and do processing for each server in a list.
You can use with open() in python like this:
with open(filename, 'r') as fileContent:
listOfLines = fileContent.readlines()
Now you will have a list of every line inside of the file.
Probably also helpful would be:
for row in listOfLines:
curData = row.split(',')
This will split the content of the row at every "," and return a list.
After that you can work with the data.

Content of file not printing

I am a beginner, learning programming using python 3.7. I am running a basic program to read content of a file after writing on it. But the print function won't print out the content of the file on the terminal. Can you please correct what mistake I am making here:
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
x = work.read()
print(x)
work.close()
After the write() completes, the file's object index needs to be moved to the beginning of the file
add work.seek(0) before the read() operation
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
work.seek(0)
x = work.read()
print(x)
work.close()
You can't actually read your spam variable since it is not a file.
Instead:
work = open("NewFile.txt", "w")
work.write(spam)
work.close()

write a program that reads the content of hoilday.txt, one line at a time

I have to do this Coding Challenge on python 3.5.2.
So far here is my code:
file = open("holiday text",'r')
contents = file.read
print(contents)
file.close()
This should do the trick. Note that if the text file isn't in the same folder as the python (eg C:/Python35-32) you should specify the whole path, except if it's for some online challenge where you just provide the text file.
file = open("holiday text.txt",'r')
contents = file.read()
file.close()
print(contents)
Another way is to use the with statement which automatically opens/closes the file appropriately, like so:
with open("holiday text.txt",'r') as file:
contents = file.read()
print(contents)
If it helped, please press the arrow button for accepted answer.

Editing a .odt File using python

First off i must say i am VERY new to programming (less then a week experience in total). I set out to write a program that generates a series of documents of an .odt template. I want to use a template with a specific keyword lets say "X1234X" and so on. This will then be replaced by values generated from the program. Each document is a little different and the values are entered and calculated via a prompt (dates and other things)
I wrote most of the code so far but i am stuck since 2 days on that problem. I used the ezodf module to generate a new document (with different filenames) from a template but i am stuck on how to edit the content.
I googled hard but came up empty hope someone here could help. I tried reading the documentations but i must be honest...its a bit tough to understand. I am not familiar with the "slang"
Thanks
PS: a ezodf method would be great, but any other ways will do too. The program doesnt have to be pretty it just has to work (so i can work less ^_^)
Well i figured it out. nd finished the program. I used a ezodf to create the file, then zipfile to extract and edit the content.xml and then repacked the whole thing via a nice >def thingy< from here. I tried to mess with etree...but i couldnt figure it out...
from ezodf import newdoc
import os
import zipfile
import tempfile
for s in temp2:
input2 = s
input2 = str(s)
input1 = cname[0]
file1 = '.odt'
namef = input2 + input1 + file1
odt = newdoc(doctype='odt', filename=namef, template='template.odt')
odt.save()
a = zipfile.ZipFile('template.odt')
content = a.read('content.xml')
content = str(content.decode(encoding='utf8'))
content = str.replace(content,"XXDATEXX", input2)
content = str.replace(content, 'XXNAMEXX', input1)
def updateZip(zipname, filename, data):
# generate a temp file
tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
os.close(tmpfd)
# create a temp copy of the archive without filename
with zipfile.ZipFile(zipname, 'r') as zin:
with zipfile.ZipFile(tmpname, 'w') as zout:
zout.comment = zin.comment # preserve the comment
for item in zin.infolist():
if item.filename != filename:
zout.writestr(item, zin.read(item.filename))
# replace with the temp archive
os.remove(zipname)
os.rename(tmpname, zipname)
# now add filename with its new data
with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr(filename, data)
updateZip(namef, 'content.xml', content)

Resources