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")
Code:
opener = open("gymclub.txt", "r")
reader = opener.readline()
listPressups = [["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",]]
while reader!="":
splitting=reader.split(",")
name = splitting[0]
press_ups = splitting[1]
pull_ups = splitting[2]
reader = opener.readline()
for x in range(1,12):
listPressups[0][x].append(int(press_ups))
listPressups.sort(reverse=True)
print(listPressups)
Output:
Traceback (most recent call last):
File "C:/Users/Nutzer/Desktop/Python/practice_NEA/index.py", line 36, in <module>
listPressups[0][x].append(int(press_ups))
IndexError: list index out of range
Desired Output:
[["",75],["",74],["",73],["",67],["",66],["",58],["",45],["",33],["",30],["",25],["",10],["",8]]
What method can I use to reach my desired output?
The text file I used:
Try this:
opener = open("gymclub.txt", "r")
listPressups = []
for line in opener.readlines():
press_ups = int(line.split(",")[1])
listPressups.append(["", press_ups])
listPressups.sort(reverse=True)
opener.close()
print(listPressups)
Instead of
listPressups[0][x].append(int(press_ups))
It should be
listPressups[x][1].append(int(press_ups))
You could just start with an empty array, here: listPressups and append with just a while loop as shown below.
opener = open("gymclub.txt", "r")
reader = opener.readline()
#listPressups = [["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",],["",]]
listPressups = []
while reader!="":
splitting=reader.split(",")
name = splitting[0]
press_ups = splitting[1]
pull_ups = splitting[2]
reader = opener.readline()
listPressups.append(["",int(press_ups)]) #Here we append an empty string with each value
listPressups.sort(reverse=True)
print(listPressups)
Error:
Traceback (most recent call last):
File "son.py", line 120, in <module>
`main()`
File "son.py", line 101, in main
`temp += item`
TypeError: 'ApplyResult' object is not iterable
Code:
pool = multiprocessing.Pool(processes=int(args.process))
for i in range(int(args.process)):
result_first_round.append(pool.apply_async(Son_Algorithm, (i,)))
pool.close()
pool.join()
first_temp = []
for res in result_first_round:
first_temp.append(res)
#first_temp.append(res.get())
#Second Scan
result_final_round = []
temp = []
for item in first_temp:
temp += item
temp2 = []
for result in temp:
if not result in temp2:
temp2.append(result)
temp_result = temp2
It seems that you want to add the element item to the list temp. In that case you need to use the method append(), like this:
temp = []
for item in first_temp:
temp.append(item)
The operator += for a list only works if the second object is also a list (or at least an iterable).
Trying to replicate this repository: https://github.com/sujiongming/UCF-101_video_classification. I get the following error when I run the CNN_train_UCF101.py file.
Traceback (most recent call last):
File "CNN_train_UCF101.py", line 18, in <module>
data = DataSet()
File "D:\Clones\UCF-101_video_classification-master\UCFdata.py", line 32, in __init__
self.classes = self.get_classes()
File "D:\Clones\UCF-101_video_classification-master\UCFdata.py", line 64, in get_classes
if item[1] not in classes:
IndexError: list index out of range
part of the code referenced is as follows:
def get_data():
"""Load our data from file."""
with open('./data/data_file.csv', 'r') as fin:
reader = csv.reader(fin)
data = list(reader)
def clean_data(self):
"""Limit samples to greater than the sequence length and fewer
than N frames. Also limit it to classes we want to use."""
data_clean = []
for item in self.data:
if int(item[3]) >= self.seq_length and int(item[3]) <= self.max_frames \
and item[1] in self.classes:
data_clean.append(item)
return data_clean
def get_classes(self):
"""Extract the classes from our data. If we want to limit them,
only return the classes we need."""
classes = []
for item in self.data:
if item[1] not in classes:
classes.append(item[1])
# Sort them.
classes = sorted(classes)
# Return.
if self.class_limit is not None:
return classes[:self.class_limit]
else:
return classes
I have updated the question to give clarity on data.
When I do print (self.data) I get something like this:
['train', 'UnevenBars', 'v_UnevenBars_g22_c04', '126'], [] for each image in the dataset.
Can anyone please show me what I'm doing wrong. Thanks in advance.
Window 10
Python 3.7.6
You have a blank line in the CSV file, which is resulting in an empty list at the end of self.data.
You should skip empty items.
for item in self.data:
if len(item) < 2:
continue
if item[1] not in classes:
classes.append(item[1])
I am trying to parallel process some file by reading chunks and process each chunk by using multiprocessing libraries. Following is my code:
from multiprocessing import Pool
from itertools import islice
import traceback
#Produce key value pairs (Date, Market_Share*Market_Share)
def Map(L):
results = []
for w in L:
temp = w.split(',')
Date = temp[0]
Share = float(temp[1][:-1])
ShareSquare = str(Share*Share)
results.append((Date,ShareSquare))
return results
if __name__=='__main__':
pool = Pool(2)
f = open('C:/Users/Daniel/Desktop/Project/Optiver/atchm_9450.csv','r')
fw = open('C:/Users/Daniel/Desktop/Project/Optiver/marketshare.csv','w')
f.readline()
while True:
next_n_lines = list(islice(f,16))
if not next_n_lines:
break
else:
l = pool.map(Map,next_n_lines)
f.close()
fw.close()
However, it produces index out of range error:
Traceback (most recent call last):
File "trial.py", line 29, in <module>
l = pool.map(Map,next_n_lines)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 558, in get
raise self._value
IndexError: list index out of range
The list object I passed into the Map function is something like ['6/26/2014,68.90\n', '6/27/2014,68.84\n', '6/30/2014,68.80\n'....]
It works correctly when there is no parallelism involved (pool is not invoked).
What possibly causes this behavior?
At first glance, only those two lines can raise this exception:
Date = temp[0]
Share = float(temp[1][:-1])
Try to check that w have enough data.