How to fix the code about appending a number in the line? - python-3.x

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)

Related

"IndexError: list index out of range" when comparing object to csv file element in Python

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.

i am trying to calculate sentimental score of each syntax of csv file by using csv library

this is the error which i am getting. In the previous post i forget to put both function . In the first function i'm reading csv file and removing punctuation and send the string to second function to calculate the sentimentel score. this code give output for few row of csv file and then show this error i'm new in python
Traceback (most recent call last):
File "C:/Users/Public/Downloads/Hotelsurvey.py", line 116, in <module>
Countswordofeachsyntax()
File "C:/Users/Public/Downloads/Hotelsurvey.py", line 92, in Countswordofeachsyntax
print(findsentimentalscore(nopunct))
File "C:/Users/Public/Downloads/Hotelsurvey.py", line 111, in findsentimentalscore
ss =ss + weight
TypeError: unsupported operand type(s) for +: 'int' and 'list'
def Countswordofeachsyntax():
nopunct = ""
with open('dataset-CalheirosMoroRita-2017.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter='|')
for sys in csv_reader:
for value in sys:
nopunct = ""
for ch in value:
if ch not in punctuation:
nopunct = nopunct + ch
print(findsentimentalscore(nopunct))
def findsentimentalscore(st):
ss = 0
count = len(st.split())
mycollapsedstring = ' '.join(st.split())
print(str(mycollapsedstring.split(' ')) + " := " + str(len(mycollapsedstring.split())))
for key, weight in keywords.items():
if key in mycollapsedstring.lower():
ss =ss + weight
#print(key, weight)
res = (ss / count * 100)
return math.ceil(res)

Import to Python a specific format file line per line

How can I Import this file which contains plain text with numbers?
It's difficult to import because the first line contains 7 numbers and the second line contains 8 numbers...
In general:
LINE 1: 7 numbers.
LINE 2: 8 numbers.
LINE 3: 7 numbers.
LINE 4: 8 numbers.
... and so on
I just had tried to read but cannot import it. I need to save the data in a NumPy array.
filepath = 'CHALLENGE.001'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = fp.readline()
cnt += 1
LINK TO DATA
This file contains information for each frequency has is explained below:
You'll have to skip the blank lines when reading as well.
Just check if the first line is blank. If it isn't, read 3 more lines.
Rinse and repeat.
Here's an example of both a numpy array and a pandas dataframe.
import pandas as pd
import numpy as np
filepath = 'CHALLENGE.001'
data = []
headers = ['frequency in Hz',
'ExHy coherency',
'ExHy scalar apparent resistivity',
'ExHy scalar phase',
'EyHz coherency',
'EyHx scalar apparent resistivity',
'EyHx scalar phase',
're Zxx/√(µo)',
'im Zxx/√(µo)',
're Zxy/√(µo)',
'im Zxy/√(µo)',
're Zyx/√(µo)',
'im Zyx/√(µo)',
're Zyy/√(µo)',
'im Zyy/√(µo)',
]
with open(filepath) as fp:
while True:
line = fp.readline()
if not len(line):
break
fp.readline()
line2 = fp.readline()
fp.readline()
combined = line.strip().split() + line2.strip().split()
data.append(combined)
df = pd.DataFrame(data, columns=headers).astype('float')
array = np.array(data).astype(np.float)
# example of type
print(type(df['frequency in Hz'][0]))

How to add numbers in Text file with Strings [duplicate]

This question already has an answer here:
How to perform addition in text file bypassing strings
(1 answer)
Closed 4 years ago.
import csv
csv_file = 'Annual Budget.csv'
txt_file = 'annual_budget.txt'
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
reader = csv.reader(my_input_file)
for row in reader:
my_output_file.write(" ".join(row)+'\n')
data = []
with open(r'annual_budget.txt', 'r') as f:
reader = csv.reader(f)
header = next(reader)
for line in reader:
rowdata = map(float, line)
data.extend(rowdata)
print(sum(data)/len(data))
Trying to add the numbers in a text file with strings but error is continually thrown.
Output:
data.extend(rowdata)
ValueError: could not convert string to float:
Data Set: [1]: https://i.stack.imgur.com/xON30.png
TLDR: You're treating space delimited text as csv which is not parsing correctly by the csv module.
At the time I worked this problem out for you, you had not provided origional csv data, so for this problem I assumed your csv file contained the following data, based on your screenshot of the txt file.
Annual Budget,Q2,Q4
100,450,20
600,765,50
500,380,79
800,480,455
1100,65,4320
Now, about the code.
You're defining data = [] in a place where it is not only
not used, but also causing it to be reset to an empty
list with every loop through the file you're converting.
If we add a print statement directly under it we get this for output:
showing added print statement:
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
reader = csv.reader(my_input_file)
for row in reader:
my_output_file.write(" ".join(row)+'\n')
data = []
print(data)
Output:
[]
[]
[]
[]
[]
[]
Moving data = [] to the top of the file prevents that.
Now with the second with statement and loops you're treating the txt file you just created as a csv file. csv data is comma delimited not space delimited. The csv reader isn't parsing the row correctly. if we add a print loop to check what is coming out of the map function we can see it's not doing what you're expecting it to, which is convert it to a list of floats.
Relevent code:
for line in reader:
rowdata = map(float, line)
for element in rowdata:
print(element)
output:
Traceback (most recent call last):
File "test.py", line 17, in <module>
for element in rowdata:
ValueError: could not convert string to float: '100 450 20'
There are multiple ways to solve the problem, but I think the best is to simply skip the whole first loop where you convert it to a space delimited file. Doing so we just depend on the csv module to do it's job.
example code:
import csv
data = []
with open('Annual Budget.csv', 'r') as f:
reader = csv.reader(f) # Gets the reader
header = next(reader) # advance the reader past the header.
for line in reader:
rowdata = map(float, line)
for element in rowdata:
print(element)
Output:
100.0
450.0
20.0
600.0
765.0
50.0
500.0
380.0
79.0
800.0
480.0
455.0
1100.0
65.0
4320.0
Now we'll add your last couple lines of code back in and remove the test code:
import csv
data = []
with open('Annual Budget.csv', 'r') as f:
reader = csv.reader(f) # Gets the reader
header = next(reader) # advance the reader past the header.
for line in reader:
rowdata = map(float, line)
data.extend(rowdata)
print(sum(data)/len(data))
Which now outputs:
677.6

Python - comparing imported values

I would like to import the list from the file, read it line by line (already works). Each line containing a string representing a list.
I have to execute couple of tasks on it, however I got twisted and I dont know why below doesn't work. It gives me the following error :
ErrorCode:
Traceback (most recent call last):
File "main.py", line 8, in <module>
if len(n) != len(str(n + 1)):
TypeError: must be str, not int
f = open('listy.txt', 'r')
content = f.read().split('\n')
for n in content:
n.split(',')
## checking lengh
if len(n) != len(str(n + 1)):
print('Different lengh')
else:
print('All fine.')
Change
n.split(',')
if len(n) != len(str(n + 1)):
to:
n = n.split(',')
len(n[0]) != len(n[1]):
and don't forget to close your file with a f.close()
Better even, use with, example:
with open('listy.txt', 'r') as f:
content = f.read().split('\n')
you do not need a close() method when using with

Resources