Using CSV file in Django choices - python

I have this function that calls the choices and activates them in each Model, however, I would like to know if there is a way to use this CSV file automatically, without having to call it item by item...
def Equipe():
with open("controle_pav/static/texto/equipes.csv", 'r') as arquivo:
equipes = arquivo.read()
EQUIPE = (
('equipes', equipes.split()[0]),
('equipes', equipes.split()[1]),
('equipes', equipes.split()[2]),
)
return EQUIPE
Is there a way to use an iterator or something like that. ?
I tried to make a router with the for but I was not successful

You can use pandas to read the CSV as follows:
import pandas as pd
equipes = pd.read_csv("controle_pav/static/texto/equipes.csv", sep=" ", header=None)
equipes will be a pandas DataFrame, which supports all kinds of manipulation.

Pandas library could be your solution:
https://pandas.pydata.org/
Please explain more about your csv file and what your Equipe function should return exactly if you need further help

Related

How to display the csv file name which is read by pandas read_csv() function?

I want to display the csv file name which is read by pandas.read_csv() function. I tried the below code but I couldn't display the csv file name.
import pandas as pd
df=pd.read_csv("abc.csv")
print(df.info())
I want to display the "abc". Guide me for my situation. Thanks in advance.
The pandas.read_csv() method accepts a File object (actually any file-like object with a read() method).
And the File class has a name object that has the name of the opened file.
I see this code and situation as absolutely meaningless since you already know the file name beforehand, but for the sake of completeness, here you go:
import pandas as pd
csv_file = open("your_csv_filename.csv")
print(csv_file.name)
df = pd.read_csv(csv_file)
When you use pandas read_csv function, you get a dataframe that does not include the file name. So the solution is storing the name of the .csv in a variable, and then print it. You can check about pandas dataframe in pandas.DataFrame Documentation
import pandas as pd
name = "abc.csv"
df=pd.read_csv(name)
print(name.split(".")[0])
You can use something like this as read_csv does not save the file_name.
Using glob will give you the ability to put wildcards or regex for all the CSV files on that folder for reading.
import glob
data = {}
for filename in glob.glob("/path/of/the/csv/files/*.csv"):
data[filename.split("/")[-1].split(".")[0]] = pd.read_csv(filename)
for key, value in data.items():
print(key)
print(value.info())
print("\n\n")
filename.split("/")[-1].split('.')[0]
The above line may look complicated but it just split the file_name 2 times.

How do you read rows from a csv file and store it in an array using Python codes?

I have a CSV file, diseases_matrix_KNN.csv which has excel table.
Now, I would like to store all the numbers from the row like:
Hypothermia = [0,-1,0,0,0,0,0,0,0,0,0,0,0,0]
For some reason, I am unable to find a solution to this. Even though I have looked. Please let me know if I can read this type of data in the chosen form, using Python please.
most common way to work with excel is use Pandas.
Here is example:
import pandas as pd
df = pd.read_excel(filename)
print (df.iloc['Hypothermia']). # gives you such result

How to fetch input from the csv file in python

I have a csv (input.csv) file as shown below:
VM IP Naa_Dev Datastore
vm1 xx.xx.xx.x1 naa.ab1234 ds1
vm2 xx.xx.xx.x2 naa.ac1234 ds1
vm3 xx.xx.xx.x3 naa.ad1234 ds2
I want to use this csv file as an input file for my python script. Here in this file, first line i.e. (VM IP Naa_Dev Datastore) is the column heading and each value is separated by space.
So my question is how we can use this csv file for input values in python so if I need to search in python script that what is the value of vm1 IP then it should pickup xx.xx.xx.x1 or same way if I am looking for VM which has naa.ac1234 Naa_Dev should take vm2.
I am using Python version 2.7.8
Any help is much appreciated.
Thanks
Working with tabular data like this, the best way is using pandas.
Something like:
import pandas
dataframe = pandas.read_csv('csv_file.csv')
# finding IP by vm
print(dataframe[dataframe.VM == 'vm1'].IP)
# OUTPUT: xx.xx.xx.x1
# or find by Naa_Dev
print(dataframe[dataframe.Naa_Dev == 'xx.xx.xx.x2'].VM)
# OUTPUT: vm2
For importing csv into python you can use pandas, in your case the code would look like:
import pandas as pd
df = pd.read_csv('input.csv', sep=' ')
and for locating certain rows in created dataframe you can multiple options (that you can easily find in pandas or just by googling 'filter data python'), for example:
df['VM'].where(df['Naa_Dev'] == 'naa.ac1234')
Use the pandas module to read the file into a DataFrame. There is a lot of parameters for reading csv files with pandas.read_csv. The dataframe.to_string() function is extremely useful.
Solution:
# import module with alias 'pd'
import pandas as pd
# Open the CSV file, delimiter is set to white space, and then
# we specify the column names.
dframe = pd.read_csv("file.csv",
delimiter=" ",
names=["VM", "IP", "Naa_Dev", "Datastore"])
# print will output the table
print(dframe)
# to_string will allow you to align and adjust content
# e.g justify = left to align columns to the left.
print(dframe.to_string(justify="left"))
Pandas is probably the best answer but you can also:
import csv
your_list = []
with open('dummy.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter=' ')
for row in reader:
your_list += [row]
print(your_list)

Writing value to given filed in csv file using pandas or csv module

Is there any way you can write value to specific place in given .csv file using pandas or csv module?
I have tried using csv_reader to read the file and find a line which fits my requirements though I couldn't figure out a way to switch value which is in the file to mine.
What I am trying to achieve here is that I have a spreadsheet of names and values. I am using JSON to update the values from the server and after that I want to update my spreadsheet also.
The latest solution which I came up with was to create separate sheet from which I will get updated data, but this one is not working, though there is no sequence in which the dict is written to the file.
def updateSheet(fileName, aValues):
with open(fileName+".csv") as workingSheet:
writer = csv.DictWriter(workingSheet,aValues.keys())
writer.writeheader()
writer.writerow(aValues)
I will appreciate any guidance and tips.
You can try this way to operate the specified csv file
import pandas as pd
a = ['one','two','three']
b = [1,2,3]
english_column = pd.Series(a, name='english')
number_column = pd.Series(b, name='number')
predictions = pd.concat([english_column, number_column], axis=1)
save = pd.DataFrame({'english':a,'number':b})
save.to_csv('b.csv',index=False,sep=',')

searching a csv file and then outputting a term associating to the term

I am creating a code, that read a csvs file and search for a specific item code and then it will output the name of the item.
How would i do this?
I don't have any code yet
Thanks
You can use pandas
Install it, then try
import pandas as pd
df = pd.read_csv('yourFile.csv')
print df

Categories