Python. How to edit data in text database? - python

I have a little database text file db.txt:
(peter)
name = peter
surname = asd
year = 23
(tom)
name = tom
surname = zaq
year = 22
hobby = sport
(paul)
name = paul
surname = zxc
hobby = music
job = teacher
How to get all data section from for example tom? I want to get in variable:
(tom)
name = tom
surname = zaq
year = 22
hobby = sport
Then i want to change data:
replace("year = 22", "year = 23")
and get:
(tom)
name = tom
surname = zaq
year = 23
hobby = sport
Now add(job) and delete(surname) data:
(tom)
name = tom
year = 23
hobby = sport
job = taxi driver
And finally rewrite that changed section to old db.txt file:
(peter)
name = peter
surname = asd
year = 23
(tom)
name = tom
year = 23
hobby = sport
job = taxi driver
(paul)
name = paul
surname = zxc
hobby = music
job = teacher
Any solutions or hints how to do it? Thanks a lot!

Using PyYAML as suggested by #aitchnyu and making a little modifications on the original format makes this an easy task:
import yaml
text = """
peter:
name: peter
surname: asd
year: 23
tom:
name: tom
surname: zaq
year: 22
hobby: sport
paul:
name: paul
surname: zxc
hobby: music
job: teacher
"""
persons = yaml.load(text)
persons["tom"]["year"] = persons["tom"]["year"]*4 # Tom is older now
print yaml.dump(persons, default_flow_style=False)
Result:
paul:
hobby: music
job: teacher
name: paul
surname: zxc
peter:
name: peter
surname: asd
year: 23
tom:
hobby: sport
name: tom
surname: zaq
year: 88
Of course, you should read "text" from your file (db.txt) and write it after finished

Addendum to Sebastien's comment: use an in-memory SQLite DB. SQLite is already embedded in Python, so its just a few lines to set up.
Also, unless that format cannot be changed, consider YAML for the text. Python can readily translate to/from YAML and Python objects (an object composed of python dicts, lists, strings, real numbers etc) in a single step.
http://pyyaml.org/wiki/PyYAML
So my suggestion is a YAML -> Python object -> SQLite DB and back again.

Related

Printing variables and strings in Python

I am trying to print the following lines :
'My name is John Smith.'
'My name is John Smith, and I live in CHICAGO'
and I live in chicago'
My code below :
name = 'John Smith'
age = 25
location = 'CHICAGO' # change this to lower case when printing
print('My name is %s.')
print('My name is %s, and I live in %s' )
print(f'My name is {name}.')
'and I live in location.lower()
How can I get the results from the top?
#!/usr/bin/env python3
name = 'john smith'
age = 25
location = 'chicago'
print ('My name is %s, and I live in %s. I am %s years old.' % (name, location, str(age)))
Output:
My name is john smith, and I live in chicago. I am 25 years old.
By the way i recommend you to read this article: https://realpython.com/python-string-formatting/
You can use f-strings for all of them. Use the lower() method to convert the location to lowercase.
print(f'My name is {name}')
print(f'My name is {name}, and I live in {location}')
print(f'and I live in {location.lower()}')

Read multiple files, dictionary value gets overwritten

When I was reading multiple files and exporting it, I realised that the values on these 4 column got overwritten by the latest value. Every file has the same iat cell location. I will like to know if this can be looped and values not getting overwritten.
name = df.iat[1,1]
age = df.iat[2,1]
height = df.iat[2,2]
address = df.iat[2,3]
Details = {'Name':name, 'Age':age,'Height':height,'Address':address}
df1 = pd.Series(Details).to_Frame()
df1 = df1.T
For example,
(1st Data):
Name: John
Age: 20
Height: 1.7m
Address: Bla Bla Bla
(2nd Data):
Name: Jack
Age: 21
Height: 1.7m
Address: Blah Blah Blah
(3rd Data):
Name: Jane
Age: 20
Height: 1.62m
Address: Blah Blah
You can loop and append your values to list.
name, age, height, address = [], [], [], []
for df in dfs:
name.append(df.iat[1,1])
age.append(df.iat[2,1])
height.append(df.iat[2,2])
address.append(df.iat[2,3])
Details = {'Name':name, 'Age':age,'Height':height,'Address':address}
df1 = pd.DataFrame(Details)

Append a text word into a text file after searching for specific word in python

i want to read a text file and want to a specific word and then want to append some other word next to it.
For example:
I want to find first name in a file like John and then want to append last name with "John" like John Smith.
Here is the code i have written up till now.
usrinp = input("Enter name: ")
lines = []
with open('names.txt','rt') as in_file:
for line in in_file:
lines.append(line.rstrip('\n'))
for element in lines:
if usrinp in element is not -1:
print(lines[0]+" Smith")
print(element)
Thats what text file looks like:
My name is FirstName
My name is FirstName
My name is FirstName
FirstName is a asp developer
Java developer is FirstName
FirstName is a python developer
Using replace is one way to do it.
Input file (names.txt):
My name is John
My name is John
My name is John
John is a asp developer
Java developer is John
John is a python developer
Script:
name = 'John'
last_name = 'Smith'
with open('names.txt','r') as names_file:
content = names_file.read()
new = content.replace(name, ' '.join([name, last_name]))
with open('new_names.txt','w') as new_names_file:
new_names_file.write(new)
Output file (new_names.txt):
My name is John Smith
My name is John Smith
My name is John Smith
John Smith is a asp developer
Java developer is John Smith
John Smith is a python developer
search_string = 'john'
file_content = open(file_path,'r+')
lines = []
flag = 0
for line in file_content:
line = line.lower()
stripped_line = line
if search_string in line:
flag = 1
stripped_line = line.strip('\n')+' '+'smith \n'
lines.append(stripped_line)
file_content.close()
if(flag == 1):
file_content = open(file_path,'w')
file_content.writelines(lines)
file_content.close()
**OUTPUT**
My name is FirstName
My name is FirstName
My name is FirstName
FirstName is a asp developer
Java developer is john smith
FirstName is a developer

Converting a text file into csv file using python

I have a requirement where in I need to convert my text files into csv and am using python for doing it. My text file looks like this ,
Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football
I want my CSV file to have the column names as Employee Name, Employee Number , Age and Hobbies and when a particular value is not present it should have a value of NA in that particular place. Any simple solutions to do this? Thanks in advance
You can do something like this:
records = """Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football"""
for record in records.split('Employee Name'):
fields = record.split('\n')
name = 'NA'
number = 'NA'
age = 'NA'
hobbies = 'NA'
for field in fields:
field_name, field_value = field.split(':')
if field_name == "": # This is employee name, since we split on it
name = field_value
if field_name == "Employee Number":
number = field_value
if field_name == "Age":
age = field_value
if field_name == "Hobbies":
hobbies = field_value
Of course, this method assumes that there is (at least) Employee Name field in every record.
Maybe this helps you get started? It's just the static output of the first employee data. You would now need to wrap this into some sort of iteration over the file. There is very very likely a more elegant solution, but this is how you would do it without a single import statement ;)
with open('test.txt', 'r') as f:
content = f.readlines()
output_line = "".join([line.split(':')[1].replace('\n',';').strip() for line in content[0:4]])
print(output_line)
I followed very simple steps for this and may not be optimal but solves the problem. Important case here I can see is there can be multiple keys ("Employee Name" etc) in single file.
Steps
Read txt file to list of lines.
convert list to dict(logic can be more improved or complex lambdas can be added here)
Simply use pandas to convert dict to csv
Below is the code,
import pandas
etxt_file = r"test.txt"
txt = open(txt_file, "r")
txt_string = txt.read()
txt_lines = txt_string.split("\n")
txt_dict = {}
for txt_line in txt_lines:
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if txt_dict.has_key(k):
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
print pandas.DataFrame.from_dict(txt_dict, orient="index")
Output:
0 1
Employee Number 12345 123456
Age 45 None
Employee Name XXXXX xxx
Hobbies Tennis Football
I hope this helps.

Define a list of object values in ConfigParser

What would be the best way to define a config file and parse it using ConfigParser defining a bunch of objects initial values (aka: constructor values)
Example:
[Person-Objects]
Name: X
Age: 12
Profession: Student
Address: 555 Tortoise Drive
Name: Y
Age: 29
Profession: Programmer
Address: The moon
And then be able to parse it in Python so I can have something like:
People = []
for person in config:
People.append(person)
Person1 = People[0]
print Person1.Profession # Prints Student
You could do something like:
[person:X]
Age: 12
Profession: Student
Address: 555 Tortoise Drive
[person:Y]
Age: 29
Profession: Programmer
Address: The moon
And then in your code:
config = ConfigParser()
config.read('people.ini')
people = []
for s in config.sections():
if not s.startswith('person:'):
continue
name = s[7:]
person = dict(config.items(s))
person['name'] = name
people.append(person)

Categories

Resources