Python 2.7.10 how to iterate files creation with different names - python

I would like to create a different number of files with Python 2.7.10. The number of them is determined by the i index ( range(X) where X is already been defined) and the name should be like :file1,file2,file3,file4...filei. Here what I was writing:
list3 = range(X)
for i in list3:
# (here I want to add the creation process)
Thanks to everyone!!

list3 = range(x)
for i in list3:
with open("File%i" % i, "w") as myfile:
#do something

You can just open files and not write anything to them to create them:
for i in range(x):
f = open("file{}".format(i), 'w')
f.close()

The question I guess is a duplicate one. Anyway for instance you can do something like that:
for x in range(3):
with open('File' + str(x) +'.txt','w') as f:
stringa = str(x) + ' Number of file written inside'
f.write(stringa)
Hope this solve your query. Have a nice day and ciao!

Related

Python: how to dynamically add a number to the end of the name of a list

In python I am appending elements to a list. The element name I am getting from an input file, so the element_name is an unknown. I would like to create a new list by adding a number to the end of the original list (dyn_list1) or even by using one of the elements in the list (element_name). How can this be achieved?
dyn_list = []
for i in range(4):
dyn_list.append(element_name)
I thought it would look something like:
dyn_list = []
for i in range(4):
dyn_list%i.append(element_name)
print(dyn_list)
But that obviously doesn't work.
To try to be clearer, what I am ultimately trying to do is create a dynamically named list, with a list name that I didn't have to explicitly define in advance.
Update:
This is not perfect, but it gets close to accomplishing what I want it to:
for i in range(4):
dyn_list.append(element_name)
globals()[f"dyn_list{i}"] = dyn_list
print("dyn_list %s" %dyn_list)
print("Dyn_list1 %s" %dyn_list1)
my_list = ["something"]
g = globals()
for i in range(1, 5):
g['dynamiclist_{0}'.format(i)] = my_list
print(dynamiclist_1)
print(dynamiclist_2)
print(dynamiclist_3)
print(dynamiclist_4)
something like that ?
I'm not sure I understand correctly, but I think you want to add the data you get by reading a txt file or something like that at the end of your list. I'm answering this assuming. I hope it helps.
list_ = ["ethereum", "is", "future"] #your list
new_list = [] #declare your new list
list_len = len(list_) #get list len
with open('dynamic.txt') as f: #read your file for dynamic string
lines = f.readlines()
while list_len: # so that the dynamic data does not exceed the length of the list
for i in range(list_len):
new_element = list_[i] + "." + str(lines[i])
new_list.append(new_element)
list_len -= 1 #Decrease to finish the while loop
for p in new_list: print(p)
You may want to use a dictionary instead of a list. You could use something like
dyn_list = {}
for i in range(4) :
element_name = ...#some code to get element_name
dyn_list[i] = element_name
Then if you want to retrieve the ith element, you can use
dyn_list[i]

Writing all outputs to a file (Python)

I have this code that should generate all possible combinations of digits and store them in a text file called Passwords4.txt. The issue here is that when I go to the text file it just shows 9999 instead of showing the numbers from 0000 to 9999.
import itertools
lst = itertools.product('0123456789', repeat=4) #Last part is equal to the password lenght
for i in lst:
print ''.join(i)
f = open('Passwords4.txt', 'w')
f.write(str(''.join(i)) +'\n')
f.close()
Can someone explain what should I do?
Your f.write is not inside the loop, so it only happens once.
You probably want the open() before the loop, and your f.write in the loop (indented, same as print).
This is the more Pythonic way of doing :
import itertools
lst = itertools.product('0123456789', repeat=4) #Last part is equal to the password lenght
with open('Passwords4.txt', 'w') as f:
for i in lst:
print ''.join(i)
f.write(str(''.join(i)) +'\n')
Python takes care of everything here ...
Re:
for i in lst:
print ''.join(i)
f = open('Passwords4.txt', 'w')
f.write(str(''.join(i)) +'\n')
By the time you open the file and write to it after the loop is finished), i has already been set to just the last result of the loop and that's why you're only getting 9999.
A fix is to do the writes within the loop, with something like:
import itertools
lst = itertools.product('0123456789', repeat=4)
f = open('Passwords4.txt', 'w')
for i in lst:
f.write(''. join(i) + '\n')
f.close()

how to modify strings in a list of strings

I would like to take a list of strings which represent individual lines entered in a CLI and put '~$ ' at the beginning so when I display them it is more clear that they are command lines. I tried this
command = # a multiline block of command lines
lines = command.split('\n')
for l in lines:
l = '~$ ' + l
for l in lines: print l
But this modifies the temporary variable l I think without going back and changing the actual value in the list. If I put the print inside of the first loop it prints with the correct values, but if I do it like shown the change isn't made. Thanks in advance for any help.
Use a list comprehension:
lines = ['~$ ' + line for line in command.split('\n')]
If you have to use a for loop, you'd use enumerate() to include an index so you can replace the individual items in the list:
for i, line in enumerate(lines):
lines[i] = '~$ ' + line
The functional way:
list(map(lambda s: '~$ ' + s, command.splitlines()))

Pythonic way to print list items

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))

Python Last Iteration in For Loop

Is there any simple way to find the Last Iteration of the for Loop in Python? I just want to convert a list to CSV.
To convert a list to CSV, use the join-function:
>>> lst = [1,2,3,4]
>>> ",".join(str(item) for item in lst)
"1,2,3,4"
If the list already contains only string, you just do ",".join(l).
Your best solution is probably to use the csv module, as suggested elsewhere. However, to answer your question as stated:
Option 1: count your way through using enumerate()
for i, value in enumerate(my_list):
print value,
if i < len(my_list)-1:
print ", followed by"
Option 2: handle the final value (my_list[-1]) outside the loop
for value in my_list[:-1]:
print value, ", followed by"
print my_list[-1]
To convert a list to csv you could use csv module:
import csv
list_of_lists = ["nf", [1,2]]
with open('file', 'wb') as f:
csv.writer(f).writerows(list_of_lists)
The 'file' file would be:
n,f
1,2
actually when a for loop in python ends the name that it bound is still accessible and bound to its last value:
for i in range(10):
if i == 3:
break
print i # prints 3
i use this trick with with like:
with Timer() as T:
pass # do something
print T.format() # prints 0.34 seconds
Not exactly what you want:
>>> for i in range(5):
print(i)
else:
print("Last i is",i)
0
1
2
3
4
Last i is 4
Edited: There is csv module in standard library, or simply ','.join(LIST)

Categories