Text File not Created in ' if ' Statement - if-statement

I am working on a little program with is able to write and load .txt files.
I am facing an issue, where the .txt file is not created when my save () function is in a "if" loop. I did used the computer's search function just in case that it was created somewhere else. Nope, nothing on the .txt file came out.
For you information, I am coding in Microsoft Visual Studio 2013 (Community), and using Windows 8.
Here are the codes:
def save (dic, filename):
out_file = open (filename, "wt")
key_list = []
for i in dic.keys():
key_list.append (i)
key_list.sort ()
for i in range(len(key_list)):
key = key_list [i]
out_file.write (key + "," + dic [key] + "\n")
out_file.close ()
filename = "dictionary.txt"
count = input ("Save (0) or Load (1): ")
if count == 0:
dic = {}
dic["1"] = "11"
dic ["2"] = "22"
dic ["3"] = "33"
dic ["4"] = "44"
dic ["5"] = "55"
save (dic, filename)

The input function returns a string. Since count is a string, count == 0 is always false. This is because the string '0' and the number 0 are not equal.
You have two options here. You can either convert the count to an integer with count = int(input('...')) and not touch your condition, or you can compare count with the string representation of 0 (count == '0').

Related

Attempted READ of key larger than file maximum key size

I'm running a program to help document what is contained in our 30+year old database. During the course of this process, I am getting the following error message:
Attempted READ of record ID larger than file/table maximum record ID size of 255 characters.
My program is working like this:
LOOP WHILE I <= NUM.FILES
RECORD = ""
FILENAME = FILE.LIST<I>
ERROR = ""
DEBUG.RECORD = ""
HAVE.LOOKED = 0
OPEN 'DICT ':FILENAME TO D.FILE THEN
OPEN FILENAME TO T.FILE THEN
STATEMENT = "SSELECT ONLY DICT ":FILENAME:' BY FIELD.NO WITH FIELD.NO >= 0 AND WITH FIELD.NO <= 900 AND WITH FIELD # ".]"'
DEBUG = ""
PRINT FILENAME
EXECUTE STATEMENT RETURNING DEBUG
LOOP WHILE READNEXT FIELDNAME DO
READ FIELD.RECORD FROM D.FILE, FIELDNAME THEN
IF LEN(FIELDNAME) > BIGGEST.KEY.LEN THEN
BIGGEST.KEY = FIELDNAME
BIGGEST.KEY.LEN = LEN(FIELDNAME)
BIGGEST.KEY.FILE = "DICT ": FILENAME
PRINT FILENAME:" ":LEN(FIELDNAME):" ":FIELDNAME
END
USE.COUNT = ""
USE.LIST = ""
USE.COUNT.STATEMENT = "SELECT ":FILENAME:" WITH ":FIELDNAME:' # ""'
DEBUGS = ""
EXECUTE USE.COUNT.STATEMENT RTNLIST USE.LIST RETURNING DEBUGS
ROW = ""
ROW<1,1> = FIELD.RECORD<2> ; *Attribute Number
ROW<1,2> = FIELDNAME ; *Field Name
ROW<1,3> = FIELD.RECORD<1> ; *Field Type
ROW<1,4> = FIELD.RECORD<10> ; *Field Size
ROW<1,5> = FIELD.RECORD<12> ; *Is Multivalued: "" = no, "Y" = Multivalued, "###" = specific multivalue
ROW<1,6> = FIELD.RECORD<13> ; *Is Subvalued: "" = no, "Y" = Subvalued, "###" = specific subvalue
ROW<1,7> = FIELD.RECORD<7> ; *Automatic data output conversion
ROW<1,8> = FIELD.RECORD<8> ; *Correlative field definition
ROW<1,9> = FIELD.RECORD<11> ; *Field description
ROW<1,10> = #SELECTED ; *Number of records that don't have this field blank
RECORD<-1> = ROW
IF ROW<1,10> < 1 THEN
READ UNUSED.FIELDS FROM CHUCK.WORK, "FILE.DEBUG.UNUSED.FIELDS" ELSE
UNUSED.FIELDS = ""
END
UNUSED.FIELDS<-1> = FILENAME:VM:ROW
WRITE UNUSED.FIELDS ON CHUCK.WORK, "FILE.DEBUG.UNUSED.FIELDS"
END
IF FIELD.RECORD<2> = 0 AND #SELECTED > 0 AND HAVE.LOOKED = 0 THEN
LOOP WHILE READNEXT KEY FROM USE.LIST DO
IF LEN(KEY) > BIGGEST.KEY.LEN THEN
BIGGEST.KEY = KEY
BIGGEST.KEY.LEN = LEN(KEY)
BIGGEST.KEY.FILE = FILENAME
PRINT FILENAME:" ":LEN(KEY):" ":KEY
END
REPEAT
HAVE.LOOKED = 1
END
END
REPEAT
END ELSE
ERROR<-1> = "Failed to open file '":FILENAME:"'"
END
END ELSE
ERROR<-1> = "Failed to open file DICT '":FILENAME:"'"
END
WRITE RECORD ON CHUCK.WORK, "FILE.":FILENAME
WRITE DEBUG.RECORD ON CHUCK.WORK, "FILE.DEBUG.":FILENAME
READ CHUCK.LOG FROM CHUCK.WORK, "CHUCK.LOG" ELSE
CHUCK.LOG = ""
END
CHUCK.LOG<-1> = "FILE '":FILENAME:"' had ":DCOUNT(RECORD,AM):" fields"
IF ERROR THEN
CHUCK.LOG<-1> = ERROR
ERRORS<-1> = ERROR
END
WRITE CHUCK.LOG ON CHUCK.WORK,"CHUCK.LOG"
CLEARSELECT
I = I + 1
REPEAT
When I look at the database directly, I can't find any record IDs or keys with more than 35 characters in the file which is causing problems, and nothing longer than 70 characters in the entire database. Can anyone help identify why these records are getting flagged in this process but aren't discoverable directly?
Below is a program I wrote to specifically find the problematic records, but it can't find the culprit
OPEN "CHUCK.WORK" TO CHUCK.WORK ELSE
PRINT "UNABLE TO OPEN CHUCK.WORK"
RETURN
END
READ FILENAME FROM CHUCK.WORK, "LISTME" ELSE
PRINT "UNABLE TO READ LISTME"
RETURN
END
NUM.FILES = DCOUNT(FILENAME,AM)
FOR I = 1 TO NUM.FILES
OPEN FILENAME<I> TO T.FILE ELSE
PRINT "UNABLE TO OPEN ":FILENAME<I>
RETURN
END
EXECUTE 'SELECT ':FILENAME<I>
LOOP WHILE READNEXT KEY DO
IF LEN(KEY) > 20 THEN
PRINT FILENAME<I>:" ":LEN(KEY):" ":KEY
END
REPEAT
NEXT I
UPDATE
One of my coworkers identified the source of the problem, even though we haven't identified how to fix the problem:
one of our files has a multivalued field which is a key used in a correlative. For some reason, Universe is trying to read the entire attribute instead of the individual multivalue as the key, which causes the long record IDs. Anyone able to see whether I am doing something wrong in my code or if there is some setting in the database that we need to look at?
When you see this error it has nothing to do with the size of keys in file, it is simply that the #ID you are trying to READ is longer than 255 chars. When I have seen it usually show me what line in the source code it happened on. If you put this right before you that line you should be able to track it down.
IF LEN(THIS.ID) GT 255 THEN
DEBUG
END
Edit. Apparently the error in this case is does not reference a line number. I was not sure if this was omitted for clarity or was some difference in the UniVerse flavor, but I now believe its absence is a hint that the error message is coming from the shell and not that the interpreter.
OPEN '','VOC' TO FILE.VOC ELSE STOP "CANNOT OPEN FILE VOC"
STMT = "SELECT VAL WITH ":STR("A",256):" EQ 0"
EXECUTE STMT RTNLIST USE.LIST RETURNING DEBUGS
CRT "**************************************"
READ TEST FROM FILE.VOC,STR("A",256) ELSE NULL
END
Which on my system outputs this.
>RUN TEST.SC TEST.LONG.ID
Attempted READ of record ID larger than file/table maximum
record ID size of 255 characters.
RetrieVe: syntax error. Unexpected sentence without filename. Token was "".
Scanned command was SELECT 'VAL' WITH 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' EQ '0'
**************************************
Program "TEST.LONG.ID": Line 5, Attempted READ of record ID larger than file/t
able maximum
record ID size of 255 characters.
>
The first looks like your error message and would point to one of the dynamic SELECT statements you are building. #ID is synonymous with with record key and to carry the analogy a little further, it appears that you are trying to unlock your bike with one of those comically large "Keys to the City".

python script returning list with double bracket

I have the following code in python 3. I'm trying to read a text file and output a list of numerical values. These values will then be used when searching through a number of pdf invoices.
Here is what I have for the text file portion:
txt_numbers = []
for file in os.listdir(my_path):
if file[-3:] == "txt":
with open(my_path + file, 'r') as txt_file:
txt = txt_file.readlines()
for line in txt:
# get number between quotes
num = re.findall(r'(?<=").*?(?=")', line)
txt_numbers.append(num)
for c, value in enumerate(txt_numbers, 1):
print(c, value)
Here is what is the output:
[[], ['51,500.00'], ['6,000.00'], ['77,000.00'], ['37,000.00']]
Question: How do I remove the "[" from within the list. I would like to have just ['51,500.00', '6,000.00', etc...]
I tried doing new_text_numbers = (", ".join(txt_numbers)) and then print(new_text_numbers)
Problem: I was appending a list with a list, which is allowed in python just not what I wanted.
Added lines:
new_num = (", ".join(num))
txt_numbers.append(new_num)
Solution:
txt_numbers = []
for file in os.listdir(my_path):
if file[-3:] == "txt":
with open(my_path + file, 'r') as txt_file:
txt = txt_file.readlines()
for line in txt:
# get number between quotes
num = re.findall(r'(?<=").*?(?=")', line)
new_num = (", ".join(num))
txt_numbers.append(new_num)
for c, value in enumerate(txt_numbers, 1):
print(c, value)

How do I dynamically search for text in a file and write to another file

I'll try to be as specific as I can. Keep in mind I just started learning this language last week so I'm not a professional. I'm trying to make a program that will read a vocabulary file that I created and write the definition for the word to another preexisting file with a different format.
Example of the two formats and what I'm trying to do here:
Word 1 - Definition
Word 1 (page 531) - Definition from other file
What I'm currently doing with it is I'm opening both files and searching a word based on user input, which isn't working. What I want to do is I want the program to go into the output file and find the word, then find the same word in the input file, get the definition only, and paste it into the output file. Then move to the next word and loop until it finds the end of file. I really don't know how to do that so I'm currently stuck. How would you python pros here on stackoverflow handle this?
Also for those who are suspicious of my reasons for this program, I'm not trying to cheat on an assignment, I'm trying to get some of my college work done ahead of time and I don't want to run into conflicts with my formatting being different from the teachers. This is just to save me time so I don't have to do the same assignment twice.
Edit 1
Here is the full code pasted from my program currently.
import os
print("Welcome to the Key Terms Finder Program. What class is this for?\n[A]ccess\n[V]isual Basic")
class_input = raw_input(">>")
if class_input == "A" or class_input == "a":
class_input = "Access"
chapter_num = 11
elif class_input == "V" or class_input == "v":
class_input = "Visual Basic"
chapter_num = 13
else:
print("Incorrect Input")
print("So the class is " + class_input)
i = 1
for i in range(1, chapter_num + 1):
try:
os.makedirs("../Key Terms/" + class_input + "/Chapter " + str(i) + "/")
except WindowsError:
pass
print("What Chapter is this for? Enter just the Chapter number. Ex: 5")
chapter_input = raw_input(">>")
ChapterFolder = "../Key Terms/" + class_input + "/Chapter " + str(chapter_input) + "/"
inputFile = open(ChapterFolder + "input.txt", "r")
outputFile = open(ChapterFolder + "output.txt", "w")
line = inputFile.readlines()
i = 0
print("Let's get down to business. Enter the word you are looking to add to the file.")
print("To stop entering words, enter QWERTY")
word_input = ""
while word_input != "QWERTY":
word_input = raw_input(">>")
outputArea = word_input
linelen = len(line)
while i < linelen:
if line[i] == word_input:
print("Word Found")
break
else:
i = i + 1
print(i)
i = 0
inputFile.close()
outputFile.close()
Not a python pro , however, I will try to answer your question.
output=[]
word=[]
definition=[]
with open('input.txt','r') as f:
for line in f:
new_line=re.sub('\n','',line)
new_line=re.sub('\s+','',line)
word.append(new_line.split("-")[0])
definition.append(new_line.split("-")[1])
with open('output.txt','r') as f:
for line in f:
new_line=re.sub('\n','',line)
new_line=re.sub('\s+','',line)
try:
index = word.index(new_line)
print index
meaning = definition[index]
print meaning
output.append(new_line+" - "+meaning)
except ValueError as e:
output.append(new_line+" - meaning not found")
print e
f=open("output.txt","w")
f.write("\n".join(output))
f.close()
Here, input.txt is the file where word and definition is present.
output.txt is the file which has only words ( it was unclear to me what output.txt contained I assumed only words ).
Above code is reading from output.txt , looking into input.txt and gets the definition if found else it skips.
Assumption is word and definition are separated by -
Does this helps?

Why does this code only read the first line rather than the whole .txt file?

I have a code here on Python 2.7 that is supposed to tell me the frequency of a letter or word within a single text file.
def frequency_a_in_text(textfile, a):
"""Counts how many "a" letters are in the text file.
"""
try:
f = open(textfile,'r')
lines = f.readlines()
f.close()
except IOError:
return -1
tot = 0
for line in lines:
split = str(line.split())
k = split.count(s)
tot = tot + k
return tot
print frequency_a_in_text("RandomTextFile.txt", "a")
There's a little bit of extra coding in there - the "try" and "except", but that's just telling me that if I can't open the text file, then it'll return a "-1" to me.
Whenever I run it, it seems to just read the first line and tell me how many "a" letters there are.
You are returning out of the function after the first iteration of your loop.
The return statement should be outside of the loop.
for line in lines:
split = str(line.split())
k = split.count(s)
tot = tot + k
return tot

Python CSV export writing characters to new lines

I have been using multiple code snippets to create a solution that will allow me to write a list of players in a football team to a csv file.
import csv
data = []
string = input("Team Name: ")
fName = string.replace(' ', '') + ".csv"
print("When you have entered all the players, press enter.")
# while loop that will continue allowing entering of players
done = False
while not done:
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ")
print (string)
file = open(fName, 'w')
output = csv.writer(file)
for row in string:
tempRow = row
output.writerow(tempRow)
file.close()
print("Team written to file.")
I would like the exported csv file to look like this:
player1,25,striker
player2,27,midfielder
and so on. However, when I check the exported csv file it looks more like this:
p
l
a
y
e
r
,
2
5
and so on.
Does anyone have an idea of where i'm going wrong?
Many thanks
Karl
Your string is a single string. It is not a list of strings. You are expecting it to be a list of strings when you are doing this:
for row in string:
When you iterate over a string, you are iterating over its characters. Which is why you are seeing a character per line.
Declare a list of strings. And append every string to it like this:
done = False
strings_list = []
while not done:
string = ""
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ") + '\n'
strings_list.append(string)
Now iterate over this strings_list and print to the output file. Since you are putting the delimiter (comma) yourself in the string, you do not need a csv writer.
a_file = open(fName, 'w')
for row in strings_list:
print(row)
a_file.write(row)
a_file.close()
Note:
string is a name of a standard module in Python. It is wise not to use this as a name of any variable in your program. Same goes for your variable file