I'm new to Python and have stumbled upon a problem while trying to code a program that searches for a line in a csv file containing the put in username.
Code:
# ...
username = input("Please put in username: ")
with open(r"C:\Users\This\Is\A\Path\user.csv", 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if username == row[0]:
data = row
print(data)
line_count += 1
f.close()
# ...
Error:
Traceback (most recent call last):
File "C:\Users\This\Is\A\Path\main.py", line 61, in <module>
if username == row[0]:
IndexError: list index out of range
Contents of user.csv
Username,Name,Age,Gender,Speechproblems,Speechspeed
bingus,Joe,22,m,n,f
My guess is that the datatypes of username and row[0] don't match up, but I wouldn't know how to check what they are because I'm not the brightest tool in the shed. The IDE I'm using is PyCharm using the Python 3.9 Interpreter.
Having a very simple to fix (I guess at least) issue with calling functions from within another function.
Here's the code:
class File_Modification:
def Start_Up():
x = 0
if x == 0:
print('Options: \n 1. Create New File \n 2. Open Existing File \n 3. Modify Existing File \n 4. Verify File')
Op_Ans = input()
if Op_Ans == '1':
Create_File()
x = 1
elif Op_Ans == '2':
Open_File()
x = 1
elif Op_Ans == '3':
print('Option Three')
x = 1
elif Op_Ans == '4':
print('Option Four')
x = 1
Start_Up()
def Create_File():
print('Create File Menu')
def Open_File():
print('Open File Menu')
def Modify_File():
print('Modify File Menu')
def Verify_File():
print('Verify File Menu')
The code is meant to open a menu, ask the user to input an option and then go to a setting to modify or create information. From the start up function (called once it has been written) the next function i.e. Create_File() gives an error that the function is not recognised.
Any one got any solutions to this error? Haven't been able to find any solutions to this yet.
This is the error I am getting:
Traceback (most recent call last):
File "C:\Users\explo\Downloads\Modify Bulk Files.py", line 1, in
class File_Modification:
File "C:\Users\explo\Downloads\Modify Bulk Files.py", line 26, in File_Modification
Start_Up()
File "C:\Users\explo\Downloads\Modify Bulk Files.py", line 12, in Start_Up
Create_File()
NameError: name 'Create_File' is not defined
Thanks everyone!
EDIT:
I've made the program work by taking out the class and only using functions. Naming all functions before the StartUp() call. This means it's all created prior.
Thanks everyone for your time. If there's any way of fixing this please note it for future reference. other wise there's my fix.
EDIT 2: Added the error that comes with it and corrected the indentations on the code.
They're in a class, so just call them as self.FunctionName()
I create a new column (name:Account) in the csv, then try to make a sequence (c = float(a) + float(b)) and for each number in sequence append to the original line in the csv, which is the value of the new column. Here is my code:
# -*- coding: utf-8 -*-
import csv
with open('./tradedate/2007date.csv') as inf:
reader = csv.reader(inf)
all = []
row = next(reader)
row.append('Amount')
all.append(row)
a =50
for i, line in enumerate(inf):
if i != 0:
size = sum(1 for _ in inf) # count the line number
for b in range(1, size+1):
c = float(a) + float(b) # create the sequence: in 1st line add 1, 2nd line add 2, 3rd line add 3...etc
line.append(c) # this is the error message: AttributeError: 'str' object has no attribute 'append'
all.append(line)
with open('main_test.csv', 'w', newline = '') as new_csv:
csv_writer = csv.writer(new_csv)
csv_writer.writerows(all)
The csv is like this:
日期,成交股數,成交金額,成交筆數,發行量加權股價指數,漲跌點數,Account
96/01/02,"5,738,692,838","141,743,085,172","1,093,711","7,920.80",97.08,51
96/01/03,"5,974,259,385","160,945,755,016","1,160,347","7,917.30",-3.50,52
96/01/04,"5,747,756,529","158,857,947,106","1,131,747","7,934.51",17.21,53
96/01/05,"5,202,769,867","143,781,214,318","1,046,480","7,835.57",-98.94,54
96/01/08,"4,314,344,739","115,425,522,734","888,324","7,736.71",-98.86,55
96/01/09,"4,533,381,664","120,582,511,893","905,970","7,790.01",53.30,56
The Error message is:
Traceback (most recent call last):
File "main.py", line 21, in <module>
line.append(c)
AttributeError: 'str' object has no attribute 'append'
Very thanks for any help!!
I'm a little confused why you're structuring your code this way, but the simplest fix would be to change the append (since you can't append to a string) to += a string version of c, i.e.
line += str(c)
or
line += ',{}'.format(c)
(I'm not clear based on how you're written this if you need the comma or not)
The biggest problem is that you're not using your csv reader - below is a better implementation. With the csv reader it's cleaner to do the append that you want to do versus using the file object directly.
import csv
with open('./tradedate/2007date.csv') as old_csv:
with open('main_test.csv', 'w') as new_csv:
writer = csv.writer(new_csv, lineterminator='\n')
reader = csv.reader(old_csv)
all = []
row = next(reader)
row.append('Line Number')
all.append(row)
line_number = 51
for row in reader:
row.append(line_number)
all.append(row)
line_number += 1
writer.writerows(all)
I am new to stack overflow and I was wondering if anyone could help me with the following question. If you know a similar question that was answered, please point me towards it. thanks:)
This is my code to create a function load_words() that creates a list of 6 letter words from the file "words.txt". I want the random.choice() to pick a random word from the list and save it into word. However, I get the error below.
import random
def load_words(filename, length):
file = open(filename, "r")
words = []
for line in file:
word = line.strip()
if len(word)== length:
words.append(word)
return words
word = random.choice(words)
print (word)
the error I get is:
Traceback (most recent call last):
File "C:\Users\mssuk\Desktop\University\Software Engineering\Assignment\assignment 1 - word guessing game\compute_score.py", line 14, in <module>
word = random.choice(words)
NameError: name 'words' is not defined
It's an indentation error. Indent your return statement by 4 spaces and the code will work.
import random
def load_words(filename, length):
file = open(filename, "r")
words = []
#Assuming there is only one word in a line
for line in file:
word = line.strip().lower()
if len(word) == length:
words.add(word)
file.close()
return words
word = random.choice(load_words(your_filename, your_length)
print(word)
I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')
the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error