Pass the value of a variable to a function in Python3 - variables

I have created a function that opens a file and reads the first line of it into a variable named 'farmer_id'. I would now like to use this 'farmer_id' variable in a second function in my script, and I'm not sure of the best way to do this. Global variables are allowed, so any solution is welcome.
I have read everything I can find on Stackoverflow on this topic, but I cannot find anything which works for my specific problem.
def get_id_from_file():
file = open('C:/Users/my.name/Documents/test.txt', 'r')
farmer_id = file.readline()

You can do like this
def any_func(former_id):
pass
def get_id_from_file():
file = open(r'C:/Users/my.name/Documents/test.txt', 'r')
farmer_id = file.readline()
return farmer_id
farmerid = get_id_from_file()
any_func(farmerid)

Related

Failed exporting df.to_csv using a variable name in the path

I am using a function MyFunction(DataName) that creates a pd.DataFrame(). After certain modifications to data, I am able to export such dataframe into csv with this code:
df.to_csv (r'\\kant\kjemi-u1\izarc\pc\Desktop\out.csv', index = True, header=True)
Creating an 'out.csv' file which is overwritten everytime the code is run. However when I try to give a specific name (for instance the name of the data used to fill in the dataframe, for multiple exports like this:
df.to_csv (fr'\\kant\kjemi-u1\izarc\pc\Desktop\{DataName}.csv', index = True, header=True)
I have this error:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
in
----> 1 MyFunction(DataName)
I am new in the programming world so any ideas of how I can overcome this problem are very welcomed. Thank you very much!
If I understand you right (and given that the fr in your code should be simply r), you want to have your to_csv statement dynamic and what is supposed to go within the brackets to change. So, assume you dataframe if df. Then, do this:
DataName = "df"
NewFinger.to_csv (r'\\kant\kjemi-u1\izarc\pc\Desktop\{}.csv'.format(DataName), index = True, header=True)
thanks for your help. In the beggining I was confused with 'NewFinger' I thought it was some sort of module I needed to install. I could not find information in google. However I solved the issue based on your suggestion actually with the following code:
DataName = "whichever name"
df.to_csv (r'\\kant\kjemi-u1\izarc\pc\Desktop\{}.csv'.format(DataName), index = True, header=True)

Correct use of append and Alignat from pylatex while pdf creating (python)

I want to save some formulas from latex in pdf
from pylatex import Document, Section, Subsection, Command,Package, Alignat
doc = Document(default_filepath='basic.tex', documentclass='article')
doc.append('Solve the equation:')
doc.append(r'$$\frac{x}{10} = 0 \\$$',Alignat(numbering=False, escape=False))
doc.generate_pdf("test", clean_tex=True)
But I get an error:
doc.append(r'$$\frac{x}{10} = 0 \\$$',Alignat(numbering=False, escape=False))
TypeError: append() takes 2 positional arguments but 3 were given
How should I solve my problem?
This answer comes late, but I guess there is no harm: The Alignat environment cannot be passed to append like that, instead the appended formula is enclosed in it. Also it is a math environment, so the $$ are not necessary.
from pylatex import Document, Section, Subsection, Command,Package, Alignat
doc = Document(default_filepath='basic.tex', documentclass='article')
doc.append('Solve the equation:')
with doc.create(Alignat(numbering=False, escape=False)) as agn:
agn.append(r'\frac{x}{10} = 0')
Output:

How to import Pandas data frames in a loop [duplicate]

So what I'm trying to do is the following:
I have 300+ CSVs in a certain folder. What I want to do is open each CSV and take only the first row of each.
What I wanted to do was the following:
import os
list_of_csvs = os.listdir() # puts all the names of the csv files into a list.
The above generates a list for me like ['file1.csv','file2.csv','file3.csv'].
This is great and all, but where I get stuck is the next step. I'll demonstrate this using pseudo-code:
import pandas as pd
for index,file in enumerate(list_of_csvs):
df{index} = pd.read_csv(file)
Basically, I want my for loop to iterate over my list_of_csvs object, and read the first item to df1, 2nd to df2, etc. But upon trying to do this I just realized - I have no idea how to change the variable being assigned when doing the assigning via an iteration!!!
That's what prompts my question. I managed to find another way to get my original job done no problemo, but this issue of doing variable assignment over an interation is something I haven't been able to find clear answers on!
If i understand your requirement correctly, we can do this quite simply, lets use Pathlib instead of os which was added in python 3.4+
from pathlib import Path
csvs = Path.cwd().glob('*.csv') # creates a generator expression.
#change Path(your_path) with Path.cwd() if script is in dif location
dfs = {} # lets hold the csv's in this dictionary
for file in csvs:
dfs[file.stem] = pd.read_csv(file,nrows=3) # change nrows [number of rows] to your spec.
#or with a dict comprhension
dfs = {file.stem : pd.read_csv(file) for file in Path('location\of\your\files').glob('*.csv')}
this will return a dictionary of dataframes with the key being the csv file name .stem adds this without the extension name.
much like
{
'csv_1' : dataframe,
'csv_2' : dataframe
}
if you want to concat these then do
df = pd.concat(dfs)
the index will be the csv file name.

Using call read within a js function

I have a slight problem I want to solve. I have the following lines of code which create 2 users which works. However the issue is that, it creates both users with the same Id from the the first line of code:
def myId = call read('classpath:karate/helpers/guid.js')
def users = function(){ karate.call('classpath:v1/api_CreateUser.feature')}
def usersResult = karate.repeat(2, users )
So I want to be able to create multiple users with different Ids. I tried the following:
* def users =
"""
function(){
var myId = null;
if(myId == null)
{
myId = call read('classpath:karate/helpers/guid.js')
}
karate.call('classpath:v1/api_CreateUser.feature');
}
"""
def usersResult = karate.repeat(2, users )
So the idea is to reset the 'myId' variable everytime to null, check if null which will be true, then call the js function which generates the id and assign the result to 'myId' variable.
Then the variable will be used on the karate.call('classpath:v1/api_CreateUser.feature') line.
Unfortunately I'm getting javascript evaluation failed error.
Anyone could help?
Thanks
Be clear about the slight difference when you are in Karate and when you are in JS. For example:
myId = call read('classpath:karate/helpers/guid.js')
This won't work. What you are looking for is:
myId = karate.call('classpath:karate/helpers/guid.js');
I recommend you read and understand the section on Karate Expressions it will save you a lot of trouble later.
When you use a JS function (that works) you should never need to worry about what you are. Just invoke it wherever, and it will "dispense" a new value. For example if you have:
* def time = function(){ return java.lang.System.currentTimeMillis() + '' }
* def first = time()
* def second = time()
Here first and second will always be different. I think now you have all you need. You are trying to access a JS variable defined in Karate from within a function, this depends on when either was initialized and I don't recommend it if you don't know what you are doing. But if you want to access the latest value of a Karate variable, the right way is to use karate.get(varNameAsString).

Variable inside a variable in Jenkinsfile

What is the correct Jenkinsfile syntax in order to use a variable value when executing command with another variable?
For example:
def lastItemIndex = "${json.items.size()-1}"
def path = "${json.items[${lastItemIndex}].assets.downloadUrl}"
echo "${path}"
First variable is lastItemIndex and second one is json.
The second row is not running properly when I tried different options.
The syntax in your second row is mostly fine. Your problem is that you are storing the return of lastItemIndex as a String and then attempting to use it as an Integer in your second row of code.
You can fix your first row with:
lastItemIndex = json.items.size() - 1
and then it will be an Integer type and def path = "${json.items[lastItemIndex].assets.downloadUrl}" will succeed.
Alternatively, you could just have the second line of code with:
def path = "${json.items[-1].assets.downloadUrl}"
to access the last element of the array.
Note that in general if you need to convert a String to an Integer within a Jenkins Pipeline via Groovy you can utilize the to_Integer method.
Thanks to Matt, eventually that what works for me:
def lastItemIndex = json.items.size()-1
def path = json.items[lastItemIndex].assets.downloadUrl