Sort integer file names in Python - python

I have file names as
When I iterate over them, it iterated in a string manner like:
1
10
11
.
.
19
2
20
.. so on. I hope you got this.
I want to iterate them over as integers not strings. Please help me write a function for it.
for i,file in enumerate(sorted(files),key=lambda x: int(os.path.splitext(file)[0]))
#CODE
But gives an error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-45-f667164b9d6e> in <module>
----> 6 for i,file in enumerate(sorted(files),key=lambda x: int(os.path.splitext(file)[0])):
TypeError: 'key' is an invalid keyword argument for enumerate()
Please help me write a function for it. Thanks in advance.

You might try converting all your files to ints first, then sort them.
import os
files = ['0.pdf', '1.pdf', '12.pdf', '15.pdf', '3.pdf', '2.pdf', ]
for i, file_as_number in enumerate(sorted(int(os.path.splitext(file)[0]) for file in files)):
print(i, file_as_number)

files = ['0.pdf', '1.pdf', '12.pdf', '15.pdf', '3.pdf', '2.pdf' ]
fileDict= {}
SortedFiles = []
for i in range(len(files)):
fileDict[int(files[i].split('.')[0])] = files[i]
for i in sorted(list(fileDict.keys())):
SortedFiles.append(fileDict[i])
print (SortedFiles)
['0.pdf', '1.pdf', '2.pdf', '3.pdf', '12.pdf', '15.pdf']

Related

takes 7 positional arguments but 8 were given error [duplicate]

Can someone please explain to me why I keep getting this error: TypeError: get_n_nouns() takes 1 positional argument but 2 were given.
I have already had a look at where my problem may be by looking at a similar question (Link) But I have adapted my code going along with the answer and yet I end up with the above error.
Here is the error in full:
Traceback (most recent call last):
File "C:/Users/...../Downloads/Comp4.1/trialTo3.py", line 21, in <module>
app.createPhrases()
File "C:/Users/...../Downloads/Comp4.1/trialTo3.py", line 15, in createPhrases
words = self.get_n_nouns(1)
TypeError: get_n_nouns() takes 1 positional argument but 2 were given
Here is the code:
import csv
class apps():
def get_n_nouns(n):
"""
Returns the n most common nouns
"""
with open("setPhrases.txt") as in_file:
reader = csv.reader(in_file)
data = [[row[0], int(row[1])] for row in list(reader)]
return sorted(data, key=lambda x: -x[1])[:n]
def createPhrases(self):
words = self.get_n_nouns(1)
for word, count in words:
print("{}: {}".format(word, count))
app = apps()
app.createPhrases()
Can someone please explain to me where I am going wrong? Any help is much appreciated.
Ok so I found out where the error was. Kind of a rookie error.
This:
def get_n_nouns(n):
Needed to be written as this:
def get_n_nouns(self, n):
I had forgot to add the self part to it. That is why I kept getting that error message.

Split a numeric string to a list of integers

I have fetched a list using pandas, but the numeric is like a numeric string. I am trying to convert it to a list of integers.
excel_frame = read_excel(args.path, sheet_name=1, verbose=True, na_filter=False)
data_need = excel_frame['Dependencies'].tolist()
print(data_need)
intStr = data_need.split(',')
map_list = map(int, intStr)
print(map_list)
I am getting the following error.
$python ExcelCellCSVRead.py -p "C:\MyCave\iso\SDG\Integra\Intest\first.xlsx"
Reading sheet 1
['187045, 187046']
Traceback (most recent call last):
File "ExcelCellCSVRead.py", line 31, in <module>
intStr = data_need.split(',')
AttributeError: 'list' object has no attribute 'split'
The target output must be like this -> [187045, 187046]. The current output is coming out like this ->['187045, 187046']
I am pretty sure I have followed suggested approach to resolve the issue, yet it is throwing error.
Regards
data_need
The problem is:
data_need = excel_frame['Dependencies'].tolist()
returns a list. So you can't split it further.
Change your existing code to this:
intStr = data_need[0].split(',') ## if you have only 1-element in data_need
map_list = list(map(int, intStr))
print(map_list)
Tested on your sample:
In [1000]: data_need = ['187045, 187046']
In [1001]: intStr = data_need[0].split(',')
In [1002]: map_list = list(map(int, intStr))
In [1003]: print(map_list)
[187045, 187046]

What is ValueError: too many values to unpack (expected 2)?

Im trying to convert midi files to csv, make changes, and then change back into midi. I wan to do this all in python using the py_midicsv module.
However, I run into an error when i try to follow the documentation on: https://github.com/timwedde/py_midicsv
#Convert back to csv
import py_midicsv
csv_string = py_midicsv.midi_to_csv("example.mid")
midi_object = py_midicsv.csv_to_midi(csv_string)
The code above is straight from the documentations but I run into the error:
ValueError Traceback (most recent call last)
<ipython-input-17-2cb6d586ec9e> in <module>
1 #Convert back to csv
2 import py_midicsv
----> 3 midi_object = py_midicsv.csv_to_midi(csv_string)
~/.local/lib/python3.6/site-packages/py_midicsv/csvmidi.py in parse(file)
44 pattern.append(track)
45 else:
---> 46 event = csv_to_midi_map[identifier](tr, time, identifier, line[3:])
47 track.append(event)
48 pattern.make_ticks_rel()
~/.local/lib/python3.6/site-packages/py_midicsv/csv_converters.py in to_AfterTouchEvent(track, time, identifier, line)
24
25 def to_AfterTouchEvent(track, time, identifier, line):
---> 26 cannel, value = map(int, line)
27 return AfterTouchEvent(tick=time, channel=channel, value=value)
28
ValueError: too many values to unpack (expected 2)
What does this error mean and how can I fix things?
cannel, value = map(int, line)
the problem is with this line.
you are trying to unpack this map object into 2 objects, but it consists of more than 2 object, so python don't know what to do with the rest of the values.
you will need to understand what this map object contains, and what data you need to get from it. try to print it and see what data it holds.

How can I create a list of all files in subdirectories while remaining the right order?

I am trying to get a list of all the files in several subdirectories. However, it shuffles the order when I do so with this code:
os.chdir = "current working directory"
filelist = listdir(".")
newlist = []
for file in filelist:
x = listdir(file)
for file2 in file:
path = join(getcwd(), file, file2)
newlist.append(path)
sorted(newlist)
When I execute this code, I get the following output:
However, I would like to remain the order had in the files, like:
When I try to sort it by integer I get the following error:
ValueError Traceback (most recent call last) in ()
----> 1 sorted(newlist, key=int) ValueError: invalid literal for int() with base 10: '/Users/michielaarts/Desktop/NEW DATASET TEST
VERSION/13_01_2016_13_30_02_4191/1'
Anyone can help? Many thanks!

Basic in Python

I'd like to write a basic program which copy the content from variable 'a' to variable 'b' but in reverse order, e.g.: a="toy" to b="yot"
My code:
a="toy"
index= len(a)
indexm=0
new=" "
while(index>0):
new[indexm]==a[index]
index=index-1
indexm=indexm+1
print(new)
I've got the following error message:
IndexError: string index out of range
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-56-c909e83737f5> in <module>()
5
6 while(index>0):
----> 7 new[indexm]==a[index]
8 index=index-1
9 indexm=indexm+1
IndexError: string index out of range
I would like to solve it without using built-in functions to learn programmer thinking.
Thank you in advance
try this:
a="toy"
index= len(a)
indexm=0
new=""
while(index>0):
new += a[index-1]
index=index-1
indexm=indexm+1
print(new)

Categories