How can I modify data using a variable field name? - python

I am trying to create a program that modify different dbf file but since each file have different field name, I am unsure if the python dbf library have the option to specify the field with string.
To modify the data without variable
dbf.write(record, CUSTOM2="Hello")
But when I tried this, it gives an error
dbf.write(record, {'CUSTOM2': "Hello"})
TypeError: write() takes 1 positional argument but 2 were given

There are a couple ways to update records in dbf files:
use the record as a context manager:
target_field = 'custom2'
with record:
record[target_field] = "Hello"
or use the write function with keywords:
target_field = 'custom2'
update = {target_field: "Hello"}
dbf.write(record, **update)

Related

Selecting interface to sniff in Python using a variable

I need to create a sniff in python using the sniff command, to collect packets entering several interfaces.
When I do it specifying the interfaces with their names with the following command:
sniff(iface=["s1-cpu-eth1","s2-cpu-eth1","s3-cpu-eth1","s4-cpu-eth1"], prn=self.recv)
It works, but if I try to use a variable (this is needed because interfaces can change depending on the context and they can be obtained through a for loop populating a variable), such as:
if_to_sniff="\"s1-cpu-eth1\",\"s2-cpu-eth1\",\"s3-cpu-eth1\",\"s4-cpu-eth1\""
sniff(iface=[if_to_sniff], prn=self.recv)
It doesn't work.
I actually tried several ways, but I always get an error saying that the device doesn't exist. How can I do this?
if_to_sniff="\"s1-cpu-eth1\",\"s2-cpu-eth1\",\"s3-cpu-eth1\",\"s4-cpu-eth1\""
This string looks like CSV format? In which case we can use Python's CSV reader to parse it for us:
import csv
if_to_sniff="\"s1-cpu-eth1\",\"s2-cpu-eth1\",\"s3-cpu-eth1\",\"s4-cpu-eth1\""
# csv.reader expects a file or a list of strings (like lines in csv file)
reader = csv.reader([if_to_sniff])
# get the first row from our 'csv'
# interfaces will be the 'columns' of that row
# (i.e. split into a list of sub strings)
interfaces = reader.__next__()
sniff(iface=interfaces, prn=self.recv)

Python convert.txt to .csv without having a specific file name

I am currently working on an application that will convert a messy text file full of data into an organized CSV. It currently works well but when I convert the text file to csv I want to be able to select a text file with any name. The way my code is currently written, I have to name the file "file.txt". How do I go about this?
Here is my code. I can send the whole script if necessary. Just to note this is a function that is linked to a tkinter button. Thanks in advance.
def convert():
df = pd.read_csv("file.txt",delimiter=';')
df.to_csv('Cognex_Data.csv')
Try defining your function as follow:
def convert(input_filename, output_filename='Cognex_Data.csv'):
df = pd.read_csv(input_filename, delimiter=';')
df.to_csv(output_filename)
And for instance use it as follow:
filename = input("Enter filename: ")
convert(filename, "Cognex_Data.csv")
You can also put "Cognex_Data.csv" as a default value for the output_filename argument in the convert function definition (as done above).
And finally you can use any way you like to get the filename (for instance tkinter.filedialog as suggested by matszwecja).
I haven't worked with tkinter, but PySimplyGUI, which to my knowledge is built on tkinter so you should have the possibility to extract the variables that correspond to the name of the file selected by the user. That's what I'm doing using PySimpleGUIon a similar problem.
Then, extract the file name selected by the user through the prompt and pass it as an argument to your function:
def convert(file):
df = pd.read_csv("{}.txt".format(file), delimiter=';')
df.to_csv('Cognex_Data.csv')

Tableau Server Api populate csv with multiple value filters

I'm trying to use the Tableau Server Client with Python to generate a csv file from a particular view which has a filter with multiple options, as shown in the image below.
Is it possible to specify multiple values in the CSVRequestOptions for the same filter?
I've tried to call the vf method multiple times with the same filter name (client) as the first parameter, but it only returns the data for the latter one.
def view_populate_csv(view_item):
csv_req_option = TSC.CSVRequestOptions()
csv_req_option.vf("client", "client1")
csv_req_option.vf("client", "client2")
csv_req_option.vf("client", "client3")
server.views.populate_csv(view_item, csv_req_option)
with open("./view_data.csv", "wb") as f:
f.write(b"".join(view_item.csv))
Also tried to add only the "(All)" option, but it won't return anything
csv_req_option.vf("client", "(all)")
csv_req_option.vf("client", "client1,client2,client3")

how to update a record with the dbf module

How can I update a record in a dbf with the dbf module : https://pypi.python.org/pypi/dbf
Here is what I tried:
table2 = dbf.Table(filename, codepage="cp1252")
table[0].name = "changed"
But I get:
File "<input>", line 1, in <module>
File "/venv/lib/python3.4/site-packages/dbf/ver_33.py", line 2508, in __setattr__
raise DbfError("unable to modify fields individually except in `with` or `Process()`")
dbf.ver_33.DbfError: unable to modify fields individually except in `with` or `Process()`
I managed to read and append but not to modify data, how can I do that?
Writing data to records can be accomplished in a few different ways:
using the record as a context manager:
with table[0] as rec:
rec.name = "changed"
using the dbf.Process function to deal with several records in a loop:
for rec in Process(my_table):
rec.name = rec.name.title()
using the write function in the dbf module:
dbf.write(some_record, name='My New Name')
I did it this way to enhance both safety and performance.
OK, soo I didn't understand the "with or process" part but here is how I managed to get my way:
dbf.write(table[0],name="changed")
found there, this fork had more documentation https://bitbucket.org/ltvolks/python-dbase
this should be safer Search in DBF and update record

Creating list of dictionary not working

I am trying to create an array of hash in python but it is not working
data = ["long","short","fanouts"]
app = []
for da in data:
app.append(app[name] = da)
output
File "test.py", line 5
app.append(app[name] = da)
SyntaxError: keyword can't be an expression
Please could anyone help me with correct code i am new to python
When you write
abc(x=y)
the interpreter reads that as trying to call a function with a keyword argument. So reading your line
app.append(app[name] = da)
it thinks you have a keyword argument app[name], which does not make sense as a keyword argument.
If you want to append a dict to your list, you could do it like this:
app.append({name:da})
as long as name and da are existing variables.
Try this:
data = ["long","short","fanouts"]
app = []
for da in data:
app.append({name: da})
Depends on what you want app[name] to be (assuming app is a dict). Either
app[name].append(da)
or
app.update(name=da)

Categories

Resources