Appending to dictionary in text file in Python inside the brackers {} - python

I am trying to append a message along with a name to an empty dictionary in a text file.
def tweeting():
f = open('bericht.txt', 'a')
message = input('Put in message: ')
name = input('Put in your name: ')
if name == '':
name = 'Anonymous'
tweet = name + '; ' + message
f.write(tweet)
f.close()
tweeting()
The result I am getting is this:
Tweets = {
}David; Hello everyone
The message goes after the brackets {}. Is there a way to put the message inside the brackets {} ?
Thanks for the help.

Try the following. Just take care of the quotes in name and message, if you want the text in your file to be as a dictionary. If they are not typed by user, they must be added to t before t is written in the file:
def tweeting():
with open('bericht.txt') as f:
t=f.read()
if ':' in t: #that means that t has other elements already
t=t[:-1]+','
else:
t=t[:-1]
message = input('Put in message: ')
name = input('Put in your name: ')
if name == '':
name = 'Anonymous'
t += name + '; ' + message + '}'
with open('bericht.txt', 'w') as f:
f.write(t)

you have not entered any brackets as such. Just add brackets as follows -
def tweeting():
f = open('bericht.txt', 'a')
message = input('Put in message: ')
name = input('Put in your name: ')
if name == '':
name = 'Anonymous'
tweet = '{' + name + '; ' + message + '}'
f.write(tweet)
f.close()
tweeting()
Add '\n' if you want it in different lines.

Related

Adding spaces to morses letters translation in python

Hello I have written this code in order to translate user input in morses alphabet and write it in a file , but I have 1 problem: It doesn't have spaces between each letter.Thank you in advance I can re-explain the problem if needed.
import re
def txt_2_morse(msg):
morse = {
'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---',
'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---',
'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--',
'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
'5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
'0':'-----', ' ':'/'}
return "".join([morse.get(c.upper(), ' ') for c in msg])
while True:
user_input = input('Input your hidden message!')
regex_matcher= re.compile("/[a-z]+[A-Z]+[0-9]/g")
if (regex_matcher.search(user_input) == False ):
user_input
else:
f = open("myfile.txt", "w")
f.write(txt_2_morse(user_input + "\n"))
f.close()
break
How can i add space after each letter/number after its written in the file
since that code that generate the file body is
"".join([morse.get(c.upper(), ' ') for c in msg])
All you need to do is to use a space instead of empty string
" ".join([morse.get(c.upper(), ' ') for c in msg])

Python Unittest testing program with input and output file

I made a program which has one function. This function has a file as an input and function writes result to output. I need to test if the my result is the same as expected. Below you can find a code of a program:
import os
def username(input):
with open(input, 'r') as file:
if os.stat(input).st_size == 0:
print('File is empty')
else:
print('File is not empty')
for line in file:
count = 1
id, first, middle, surname, department = line.split(":")
first1 = first.lower()
middle1 = middle.lower()
surname1 = surname.lower()
username = first1[:1] + middle1[:1] + surname1
username1 = username[:8]
if username1 not in usernames:
usernames.append(username1)
data = id + ":" + username1 + ":" + first + ":" + middle + ":" + surname + ":" + department
else:
username2 = username1 + str(count)
usernames.append(username2)
data = id + ":" + username2 + ":" + first + ":" + middle + ":" + surname + ":" + department
count += 1
with open("output.txt", "a+") as username_file:
username_file.write(data)
usernames = []
if __name__ == '__main__':
username("input_file1.txt")
username("input_file2.txt")
username("input_file3.txt")
with open("output.txt", "a+") as username_file:
username_file.write("\n")
How do I write an unittest on this type of program? I tried this but it gave me this error "TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper" . Code of my test is below:
import unittest
import program.py
class TestProgram(unittest.TestCase):
def test_username(self):
i_f = open("input_file1.txt", 'r')
result = program.username(i_f)
o_f = open("expected_output.txt", 'r')
self.assertEqual(result, o_f)
if __name__ == '__main__':
unittest.main()
I would be really happy if you could help me!!!
You didn't read the file, just pass the IO object.
Edit the TestProgram and add .read()
class TestProgram(unittest.TestCase):
def test_username(self):
i_f = open("input_file1.txt", 'r').read() # read the file
result = program.username(i_f)
o_f = open("expected_output.txt", 'r').read()
self.assertEqual(result, o_f)
you can also use with-as for automatic closing the file.

Python: How can i search for a whole word in a .txt file?

ive been searching for ages for a solution on my problem:
When a user types in a name, which is already saved in a .txt file, it should print "true".
If the username is not already existing it should add the name, the user typed in.
The Problem is, that it even prints out true when the typed name is "Julia", but "Julian" is already in the list. I hope you get my point.
I already read maaany solutions here on stackoverflow but nothing worked for me when working with a .txt file
My code:
import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(paste) != -1:
print("true")
else:
names_file.write("\n" + username)
print(username + " got added to the list")
names_file.close()
username = input("username: ")
found = False
with open("names_file.txt", "r") as file:
for line in file:
if line.rstrip() == username:
print("true")
found = True
break
if not found:
with open("names_file.txt", "a") as file:
file.write( username + "\n")
print(username + " got added to the list")
You could add the newline after the name and search for the name with the newline character:
import mmap
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes('\n' + username + '\n', 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(paste) != -1:
print("true")
else:
names_file.write('\n' + username + '\n')
print(username + " got added to the list")
names_file.close()
This will not work for names with spaces inside -- for such cases you'll have to define different separator (also if all names begin with a capital letter and there are no capital letters in the middle of the name then you could spare the newline before the name)
Try this i have updated my answer.
import mmap
import re
status = False
username = input("username: ")
names_file = open("names_file.txt", "a")
paste = bytes(username, 'utf-8')
with open("names_file.txt", "rb", 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
for f in file:
f = f.strip()
if f == paste:
print("true")
status = True
if status == False:
names_file.write("\n" + username)
print(username + " got added to the list")
names_file.close()

how do i save data to a text file mainly what i have written in record

New to python, need to store this data to a text file. mainly my record but comes up with concat error (tuple) in the recsave.write line. any help or suggestions or just done completely wrong
print (' Title ')
name = 'y'
while name == 'y':
print (' Enter the name of the sender: ')
sender = input("\n")
# add name of reciever #
print (' Enter the name of the reciever: ')
reciever = input("\n")
# how much would you like to send #
print (' How much would you like to send :$ ')
amount = input("\n")
record = (sender, 'sent :$',amount, 'to', reciever, "\n" )
recsave = open('Transaction History.txt', 'w')
recsave.write(record + '\n')
recsave.close()
print (str(record, "\n"))
name = input (' Are there anymore transactions? ( Enter y or n ): ')
would like to get it so when open the text file. you get
name sent $amount to name
also needs to include time stamp :(
aslo each time the loop runs saves each loop to the record
Create one string with all information instead of tuple and write it
import datetime
dt = datetime.datetime.now()
record = "{} : {} sent :${} to {}\n".format(dt, sender, amount, reciever)
recsave = open('Transaction History.txt', 'a')
recsave.write(record)
recsave.close()
print(record)
Use mode "a" (append) instead of "w" (write) to add new record to existing records in file.
w will remove old information.
In record you add "\n" so you don't have to add it in write()
But you could create function to do it and then you can use it in different places
import datetime
def log(message):
dt = datetime.datetime.now()
line = "{} : {}\n".format(dt, message)
recsave = open('Transaction History.txt', 'a')
recsave.write(line)
recsave.close()
print(line)
#----
log("start program")
record = "{} sent :${} to {}".format(dt, sender, amount, reciever)
log(record)
log("end program")
There is standard module logging to create log or file with history.

having trouble converting dictionary elements (string) into int

Having a little trouble converting the two elements that are in a tuple inside of a dictionary into int values. the keys of the dictionary are country name and the tuple of info is (the area, the population). This is what i have so far :
def _demo_fileopenbox():
msg = "Pick A File!"
msg2 = "Select a country to learn more about!"
title = "Open files"
default="*.py"
f = fileopenbox(msg,title,default=default)
writeln("You chose to open file: %s" % f)
countries = {}
with open(f,'r') as handle:
reader = csv.reader(handle, delimiter = '\t')
for row in reader:
countries[row[0]] = (row[1].replace(',', ''), row[2].replace(',', ''))
for i in countries:
int((countries[i])[0])
int((countries[i])[1])
#while 1:
# reply = choicebox(msg=msg2, choices= list(countries.keys()) )
# writeln(reply + "-\tArea: " + (countries[reply])[0] + "\tPopulation: " + (countries[reply])[1] )
but i keep getting this error :
int((countries[i])[0])
ValueError: invalid literal for int() with base 10: ''
any ideas how to fix this or a better way to do this:

Categories

Resources