Adding to user input in python - python

I'm trying to have the use enter an input for a file name, what I would like to do is just have the user type in the name of the file without the extension. Since the only applicable file will be a .txt file it seems redundant to have the user type the extension, so I would like to add the file extension with the code this is what I have so far:
def create_bills(filename, capacity):
f = open(filename)
mytable = mkHashTable(capacity)
for line in f:
txt = line.strip().split(' $')
person = Person(txt[0], txt[1])
if not person.name in keys(mytable):
mytable = put(mytable, person.name, person.bill)
elif person.name in keys(mytable):
index = indexOf(mytable, person.name)
else:
pass
def main():
capacity = int(input("Size of Hashtable: "))
file = input("Enter file to be read: ")
filename = (file +'.txt')
create_bills(filename, capacity)
I am unsure of how to actually approach this problem and add the .txt to the user input.
Example:
Please enter a file name:
help
.... help.txt
error:
Traceback (most recent call last):
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 30, in <module>
main()
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 28, in main
create_bills(filename, capacity)
File "C:/Users/Th3M1k3/Desktop/python/beeb lab/bieberhash.py", line 12, in create_bills
f = open(filename, '.txt')
ValueError: invalid mode: '.txt'

In main you are already adding .txt to the file name entered by the user. You do not need to add it again in the open call in create_bills().

Related

I am unable to create multiple files with this code, what is wrong?

So I'm trying to write a program that takes names from a list and adds it to a letter. A text file is created for each name for the letter however the code seems to stop working at that point.
letter = []
names = []
file = open("Input/Letters/starting_letter.txt", "r")
letter = file.readlines()
file.close()
name1 = open("Input/Names/invited_names.txt", "r")
names = name1.readlines()
name1.close()
for name in names:
create_letter = open(f"{name}.txt", "w")
for line in letter:
line = line.replace("[name],", f"{name},")
create_letter.write(line)
create_letter.close()
I get the error message
Traceback (most recent call last):
File "C:\Users\Default User\PycharmProjects\Mail Merge Project Start\main.py", line 10, in <module>
create_letter = open(f"{name}.txt", "w")
OSError: [Errno 22] Invalid argument: 'Aang\n.txt'
Is there a problem with the way I am creating the files?
You can't have newlines in your file name. It is invalid in your OS/filesystem.
Remove them with:
open(f"{name.strip()}.txt", "w")
Or:
open(f"{name.replace('\n', '')}.txt", "w")

Functions, File handling

I made this code, but when I try to append, I get the following message:
Traceback (most recent call last):
File "main.py", line 38, in <module>
main()
File "main.py", line 9,in main
elif what == 'a': append(thisFile)
File "main.py", line 27, in append
for record in range(5):file.write("New "+str(record)+"\n") and file.close()
ValueError: I/O operationon closed file.

When I try to create or read a file it turns out fine, it's just when I append (or add, as the code says). What's wrong?
def main():
print("Simple text files in Python")
thisFile = input('file name?: ')
q = 0
while q != 1:
q = 1
what = input('What do you want to do? (create, add, display): ')[:1]
if what == 'c': create(thisFile)
elif what == 'a': append(thisFile)
elif what == 'd': read(thisFile)
else:
print('Invalid choice, pick another: ')
q = 0
def create(filename):
print("Creating file ...")
file=open(filename,"w")
i = 'y'
while i == 'y':
file.write(input('what do you want to write?') + '\n')
i = input('one more line?(y/n): ').lower()
file.close()
def append(filename):
print("Adding to file ...")
file=open(filename,"a")
for record in range(5):file.write("New "+str(record)+"\n") and file.close()
def read(filename):
print("Reading file ...")
file=open(filename,"r")
for record in file:
text=record
print(text)
file.close()
do = 'y'
while do == 'y':
main()
do = input('Any other functions?:(y/n): ')
As pointed by #jonrsharpe as a comment, the problem is you explicity close the file in the statement below:
for record in range(5):file.write("New "+str(record)+"\n") and file.close()
As stated in the docs
"f.write(string) writes the contents of string to the file, returning
the number of characters written."
So when you are writing to the file it's returning a number different of zero, which is used as "True" value by the "and" operator. Because the first value is "True", the second expression "file.close()" is evaluated and the file is closed. So on the next iteration it tries to write to a file that is no longer opened and you receive the error.

json file load issue using Python

I was try to dump and load dictionary to json file using Python. I can dump file without a problem. However, when i try to load file into temp dictionary, error occur. I can not figure out the issue, Can anyone can help me on this ?Thanks
import os
import json
def get_stored_birth():
filename ='C:/Users/Sam/name.json'
temp = {}
with open(filename,'r+') as f_obj1:
temp =json.load(f_obj1)
print(temp.get(name),"is the birthday of",name)
def get_new_birth():
birth=str(input())
my_dict[name]=birth
print("Birthday database updated")
filename ='C:/Users/Sam/name.json'
with open(filename,'a') as f_obj:
f_obj.write('\n')
json.dump(my_dict,f_obj)
return name
my_dict={}
def quit():
"""This function quit program"""
return quit
while True:
filename ='C:/Users/Sam/name.json'
print("Enter a name:(blank to quit)")
name= str(input())
if name=="":
exit()
if name in my_dict:
name= get_stored_birth()
else:
print("I dont have info for",name)
print("What is their birthday")
name= get_new_birth()
The traceback as follow:
Traceback (most recent call last):
File "C:\Users\Sam\Desktop\Tianxu_Assignment2\Assignment 2.py", line 45, in <module>
name= get_stored_birth()
File "C:\Users\Sam\Desktop\Tianxu_Assignment2\Assignment 2.py", line 10, in get_stored_birth
temp =json.load(f_obj1)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Sam\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 3 column 1 (char 12)
Problem solved !!!
1. replace with open(filename, 'a') as f_obj with replace with open(filename, 'w')
2.
if name in my_dict:
should not check my_dict !!! every time start a program will use new "dictionary". I move
filename ='C:/Users/Sam/name.json'
temp = {}
with open(filename,'r+') as f_obj1:
temp =json.load(f_obj1)
to main loop and check if name in temp:
Thanks guys!!!
You are appending new json to previous jsons you have created. Just substitute this line:
with open(filename,'a') as f_obj:
with this one:
with open(filename,'w') as f_obj:

Python script not working on Ubuntu, does on Windows

I have two files in a directory. One is a .CSV file and other is a Python script. Python code looks like this:
from pyx import *
import csv
import re
import sys
def write():
name = raw_input('Enter the name of .dat file: ') + '.dat'
file = open(name, "w")
for i in range(0, len(x_lista)-1):
file.write(x_lista[i])
file.write(" ")
file.write(y_lista[i])
file.write("\n")
file.close()
def read_CSV(x_lista, y_lista):
currency = raw_input('Enter the name of input .CSV file: ') + '.CSV'
#print currency
with open(currency, 'rb') as f:
reader = CSV.reader(f)
lista = list(reader)
print lista
if(currency == 'Frank' or 'USD'):
factor = 4
else:
factor = 3
for i in range (3, len(lista)-factor):
temp = (re.split(r'[";"]', (';'.join(lista[i]))))
temp1 = temp[0]
x_lista.append(temp1)
temp1 = temp[1]
y_lista.append(temp1)
print x_lista, y_lista
x_lista = []
y_lista = []
read_CSV(x_lista, y_lista)
write()
It takes what's in .CSV and by splitting/joining lists it produces a .DAT file consisting of two columns of data. Well... it does on Windows. However, when I try to compile it on Ubuntu I get this:
Enter the name of input .CSV file: Euro
Traceback (most recent call last):
File "nwb.py", line 46, in <module>
read_CSV(x_lista, y_lista)
File "nwb.py", line 22, in read_CSV
with open(currency, 'rb') as f:
IOError: [Errno 2] No such file or directory: 'Euro.CSV'
What would be the solution?
In Unix system file names are case sensitive.
For example: Euro.CSV and Euro.csv are different file names. Maybe the error is shown because of that

csv2json.py error

I am trying to run the script csv2json.py in the Command Prompt, but I get this error:
C:\Users\A\Documents\PROJECTS\Django\sw2>csv2json.py csvtest1.csv wkw1.Lawyer
Converting C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv from CSV to JSON as C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv.json
Traceback (most recent call last):
File "C:\Users\A\Documents\PROJECTS\Django\sw2\csv2json.py", line 37, in <module>
f = open(in_file, 'r' )
IOError: [Errno 2] No such file or directory: 'C:\\Users\\A\\Documents\\PROJECTS\\Django\\sw2csvtest1.csv'
Here are the relevant lines from the snippet:
31 in_file = dirname(__file__) + input_file_name
32 out_file = dirname(__file__) + input_file_name + ".json"
34 print "Converting %s from CSV to JSON as %s" % (in_file, out_file)
36 f = open(in_file, 'r' )
37 fo = open(out_file, 'w')
It seems that the directory name and file name are combined. How can I make this script run?
Thanks.
Edit:
Altering lines 31 and 32 as answered by Denis Otkidach worked fine. But I realized that the first column name needs to be pk and each row needs to start with an integer:
for row in reader:
if not header_row:
header_row = row
continue
pk = row[0]
model = model_name
fields = {}
for i in range(len(row)-1):
active_field = row[i+1]
So my csv row now looks like this (including the header row):
pk, firm_url, firm_name, first, last, school, year_graduated
1, http://www.graychase.com/aabbas, Gray & Chase, Amr A, Babas, The George Washington University Law School, 2005
Is this a requirement of the django fixture or json format? If so, I need to find a way to add the pk numbers to each row. Can I delete this pk column? Any suggestions?
Edit 2
I keep getting this ValidationError: "This value must be an integer". There is only one integer field and that's the pk. Is there a way to find out from the traceback what the line numbers refer to?
Problem installing fixture 'C:\Users\A\Documents\Projects\Django\sw2\wkw2\fixtures\csvtest1.csv.json': Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\django\core\management\commands\loaddata.py", line 150, in handle
for obj in objects:
File "C:\Python26\lib\site-packages\django\core\serializers\json.py", line 41, in Deserializer
for obj in PythonDeserializer(simplejson.load(stream)):
File "C:\Python26\lib\site-packages\django\core\serializers\python.py", line 95, in Deserializer
data[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
File "C:\Python26\lib\site-packages\django\db\models\fields\__init__.py", line 356, in to_python
_("This value must be an integer."))
ValidationError: This value must be an integer.
+ is used incorrectly here, the proper way to combine directory name and file name is using os.path.join(). But there is no need to combine directory where script is located with file name, since it's common to pass relative path to current working directory. So, change lines 31-32 to the following:
in_file = input_file_name
out_file = in_file + '.json'
from os import path
in_file = path.join(dirname(__file__), input_file_name )
out_file = path.join(dirname(__file__), input_file_name + ".json" )
[...]
You should be using os.path.join rather than just concatenating dirname() and filenames.
import os.path
in_file = os.path.join(dirname(__file__), input_file_name)
out_file = os.path.join(dirname(__file__), input_file_name + ".json")
will fix your problem, though depending on what exactly you're doing, there's probably a more elegant way to do it.

Categories

Resources