I'm writing a code which asks the user to enter an input for copying a folder ..
I want the code to get the number of times from the user then start copying the folder and rename it like a series like that :
How many times you want to copy folder "moh"?
5
then create 5 copies of the folder named ( 1 , 2 , 3 , 4 , 5 )
progs = int(raw_input( "Progs Number : "))
fullPath = currentDirectory + str(name)
if os.path.isdir( fullPath ):
# Directory name is legitimate and not already existent
shutil.rmtree ( fullPath )
os.mkdir( fullPath )
shutil.copy(moh, ) # This where the code should do the copying process but I don't know how to make the process repeated by the user input and rename the folder
else:
os.mkdir( fullPath )
When you want to do something N times, the way to do that is usually a loop over range(n):
for i in range(progs):
Now, that i is a number from 0-4, and you want a pathname in fullpath with the string value of i+1, right? So, translate that English to Python:
pathname = os.path.join(fullpath, str(i+1))
And now, you know what to copy to:
shutil.copy(moh, pathname)
Related
I have a folder that contains many eof extension files name I want to sort them in ordinary way with python code (as you can see in my example the name of all my files contain a date like:20190729_20190731 and they are just satellite orbital information files, then select and filtered 1th,24th,47th and.... (index ) of files and delete others because I need every 24 days information files( for example:V20190822T225942_20190824T005942) not all days information .for facility I select and chose these information files from first day I need so the first file is found then I should select 24 days after from first then 47 from first or 24 days after second file and so on. I exactly need to keep my desire files as I said and delete other files in my EOF source folder my desire files are like these
S1A_OPER_AUX_POEORB_OPOD_20190819T120911_V20190729T225942_20190731T005942.EOF
S1A_OPER_AUX_POEORB_OPOD_20190912T120638_V20190822T225942_20190824T005942.EOF
.
.
.
Mr Zach Young wrote this code below and I appreciate him so much I never thought some body would help me. I think I'm very close to the goal
the error is
error is print(f'Keeping {eof_file}') I changed syntax but the same error: print(f"Keeping {eof_file}")
enter code here
from importlib.metadata import files
import pprint
items = os.listdir("C:/Users/m/Desktop/EOF")
eof_files = []
for item in items:
# make sure case of item and '.eof' match
if item.lower().endswith('.eof'):
eof_files.append(item)
eof_files.sort(key=lambda fname : fname.split('_')[5])
print('All EOF files, sorted')
pprint.pprint(eof_files)
print('\nKeeping:')
files_to_delete = []
count = 0
offset = 2
for eof_file in eof_files:
if count == offset:
print(f"Keeping: [eof_file]")
# reset count
count = 0
continue
files_to_delete.append(eof_file)
count += 1
print('\nRemoving:')
for f_delete in files_to_delete:
print(f'Removing: [f_delete]')
staticmethod
Here's a top-to-bottom demonstration.
I recommend that you:
Run that script as-is and make sure your print statements match mine
Swap in your item = os.listdir(...), and see that your files are properly sorted
Play with the offset variable and make sure you can control what should be kept and what should be deleted; notice that an offset of 2 keeps every third file because count starts at 0
You might need to play around and experiment to make sure you're happy before moving to the final step:
Finally, swap in your os.remove(f_delete)
#!/usr/bin/env python3
from importlib.metadata import files
import pprint
items = [
'foo_bar_baz_bak_bam_20190819T120907_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120901_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120905_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120902_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120903_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120904_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120906_V2..._SomeOtherDate.EOF',
'bogus.txt'
]
eof_files = []
for item in items:
# make sure case of item and '.eof' match
if item.lower().endswith('.eof'):
eof_files.append(item)
eof_files.sort(key=lambda fname : fname.split('_')[5])
print('All EOF files, sorted')
pprint.pprint(eof_files)
print('\nKeeping:')
files_to_delete = []
count = 0
offset = 2
for eof_file in eof_files:
if count == offset:
print(f'Keeping {eof_file}')
# reset count
count = 0
continue
files_to_delete.append(eof_file)
count += 1
print('\nRemoving:')
for f_delete in files_to_delete:
print(f'Removing {f_delete}')
When I run that, I get:
All EOF files, sorted
['foo_bar_baz_bak_bam_20190819T120901_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120902_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120903_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120904_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120905_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120906_V2..._SomeOtherDate.EOF',
'foo_bar_baz_bak_bam_20190819T120907_V2..._SomeOtherDate.EOF']
Keeping:
Keeping foo_bar_baz_bak_bam_20190819T120903_V2..._SomeOtherDate.EOF
Keeping foo_bar_baz_bak_bam_20190819T120906_V2..._SomeOtherDate.EOF
Removing:
Removing foo_bar_baz_bak_bam_20190819T120901_V2..._SomeOtherDate.EOF
Removing foo_bar_baz_bak_bam_20190819T120902_V2..._SomeOtherDate.EOF
Removing foo_bar_baz_bak_bam_20190819T120904_V2..._SomeOtherDate.EOF
Removing foo_bar_baz_bak_bam_20190819T120905_V2..._SomeOtherDate.EOF
Removing foo_bar_baz_bak_bam_20190819T120907_V2..._SomeOtherDate.EOF
I am trying to build a script that copies a specified number of lines from one document to multiple other documents. The copied lines are supposed to be appended to the end of the docs. In case I want to delete lines from the end of the docs, the script also has to be able to delete a specified number of lines.
I want to be able to run the script from the command line and want to pass two args:
"add" or "del"
number of lines (counting from the end of the document)
A command could look like this:
py doccopy.py add 2 which would copy the last 2 lines to the other docs, or:
py doccopy.py del 4 which would delete the last 4 lines from all docs.
So far, I have written a function that copies the number of lines I want from the original document,
def copy_last_lines(number_of_lines):
line_offset = [0]
offset = 0
for line in file_to_copy_from:
line_offset.append(offset)
offset += len(line)
file_to_copy_from.seek(line_offset[number_of_lines])
changedlines = file_to_copy_from.read()
a function that pastes said lines to a document
def add_to_file():
doc = open(files_to_write[file_number], "a")
doc.write("\n")
doc.write(changedlines.strip())
doc.close()
and a main function:
def main(action, number_of_lines):
if action == "add":
for files in files_to_write:
add_to_file()
elif action == "del":
for files in files_to_write:
del_from_file()
else:
print("Not a valid action.")
The main function isn't done yet, of course and I have yet to figure out how to realize the del_from_file function.
I also have problems with looping through all the documents.
My idea was to make a list including all the paths to the documents i want to write in and then loop through this list and to make a single variable for the "original" document, but I don't know if that's even possible the way I want to do it.
If possible, maybe someone has an idea for how to realize all this with a single list, have the "original" document be the first entry and loop through the list starting with "1" when writing to the other docs.
I realize that the code I've done so far is a total clusterfuck and I ask a lot of questions, so I'd be grateful for every bit of help. I'm totally new to programming, I just did a Python crash course in the last 3 days and my first own project is shaping out to be way more complicated than I thought it would be.
This should do what you ask, I think.
# ./doccopy.py add src N dst...
# Appends the last N lines of src to all of the dst files.
# ./doccopy.py del N dst...
# Removes the last N lines from all of the dst files.
import sys
def process_add(args):
# Fetch the last N lines of src.
src = argv[0]
count = int(args[1])
lines = open(src).readlines()[-count:]
# Copy to dst list.
for dst in args[2:}
open(dst,'a').write(''.join(lines))
def process_del(args):
# Delete the last N lines of each dst file.
count = int(args[0])
for dst in args[1:]:
lines = open(dst).readlines()[:-count]
open(dst,'w').write(''.join(lines))
def main():
if sys.argv[1] == 'add':
process_add( sys.argv[2:] )
elif sys.argv[1] == 'del':
process delete( sys.argv[2:] )
else:
print( "What?" )
if __name__ == "__main__":
main()
I'm trying to write a program that finds the number of different items counting the numbers of folders. And the number of each item counting the number of photos inside of each of this folders.
Once I have that I would like to make a loop that uses a different item for every iteration. For example if I have 3 different items I would like to list the first item from the first type, then the second and so on. Like this:
y=0
num=[]
for dir in next(os.walk('.'))[1]:
for folder in os.listdir(dir):
if folder.startswith("photos"):
num.append(0)
for file in os.listdir(dir+"\\"+folder):
if file.endswith(".jpg"):
num[y]+=1
y +=1
for every item since there are no more items (everyone has a diferent number)
do
for dir in next(os.walk('.'))[1]:
for folder in os.listdir(dir):
if folder.startswith("photos"):
num.append(0)
for file in os.listdir(dir+"\\"+folder):
if file.endswith(".jpg"):
What would be the correct way?
I've come with this for now, but not what I want as you can see:
y=0
num=[]
for dir in next(os.walk('.'))[1]:
for folder in os.listdir(dir):
if folder.startswith("photos"):
num.append(0)
for file in os.listdir(dir+"\\"+folder):
if file.endswith(".jpg"):
num[y]+=1
y +=1
print (num)
print (len(num))
for dir in next(os.walk('.'))[1]:
for folder in os.listdir(dir):
if folder.startswith("photos"):
for file in os.listdir(dir+"\\"+folder):
if file.endswith(".jpg"):
this could be and example of the tree directory
flowers (would be item 1)
-photos
photo1
photo2
-otherthing
books (would be item 2)
-photos
photo1
otherthing (no item because has no photos folder inside)
oterthing (no item because has no photos folder inside)
-videos
How to open a file from the list of given files based on the user's input which is an integer
print("Enter 1.tp.txt\n2.c17testpat.pat\n3.c432testpat.pat\n4.c499testpat.pat\n5.c1335testpat.pat\n6.c6228testpat.pat")
user = input("Enter a number")
if user == 1:
filename = "tp.txt"
elif user == 2:
filename = "c17testpat.pat"
elif user == 3:
filename = "c432testpat"
elif user == 4:
filename = "c499testpat.pat"
elif user == 5:
filename = "c1355testpat.pat"
elif user == 6:
filename = "c6288testpat.pat"
fp = open(filename)
is there any other way to do it in python
this caused NameError: name 'filename' is not defined
You could store the file list as a Python list, like so:
files = ["filename_1", "filename_2", "filename_3"]
Then to print them, you would use a for loop:
for i, s in enumerate(files): # Use enumerate because we need to know which element it was
print(str(i + 1) + ": "+ s) # i + 1 because lists start from 0
To make sure your input is a number, use a while loop that exits only if the input is a valid number:
while True:
inp = input()
if inp.isdigit():
filename = files[int(inp) - 1] # - 1 because lists start from 0
break
else:
print("Enter a number")
You'll still need to make sure the number is not too big (or small, for that matter).
probably because you need to convert user to int first (might be a string as written). Also you should probably finish with a default case to throw an error if the user inputs a non sensical value...
As the question indicates a strong will to learn coding and already tried something, I offer a variant that works for python version 3 (in version 2 one would need raw_input instead of input and a future import to declare the print function):
#! /usr/bin/env python3
import sys
names_known = ( # Hints 1 and 2
None, "tp.txt", "c17testpat.pat", "c432test.pat",
"c499testpat.pat", "c1355testpat.pat", "c6288testpat.pat")
options_map = dict(zip(range(len(names_known)), names_known)) # 3
print("Enter:")
for choice, name in enumerate(names_known[1:], start=1): # 4
print('%d.%s' % (choice, name))
user_choice = input("Enter a number") # 5
try: # 6
entry_index = int(user_choice)
except:
sys.exit("No integer given!")
if not entry_index or entry_index not in options_map: # 7
sys.exit("No filename matching %d" % (entry_index,))
with open(options_map[entry_index]) as f: # 8
# do something with f
pass
Many things still can go wrong, and any error will need the user to restart (no while loops etc.), but some achievements
Have the names only stored once (here I picked a tuple)
Keep the 1 as first number in user interface (insert dummy at index 0)
Derive a dict from the tuple storing the names (dict offers fast lookup)
Build the user interface info from the name tuple (ignoring the dummy)
Separate input from validation
Check domain type first (integer). If fails exit early via sys.exit and give info
Check domain membership otherwise exit with info
open the resource filename targets in a context block so you do not forget to close when done with the processing
Not python but worth to know how to use it via bash.
A simple bash sample that list a folder content and let's user choose the file by the index.
# menu.sh
# usage: bash menu.sh FOLDER
select FILENAME in $1/*;
do
case $FILENAME in
"$QUIT")
echo "Exiting."
break
;;
*)
echo "You picked $FILENAME ($REPLY)"
chmod go-rwx "$FILENAME"
;;
esac
done
Credit http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_06.html
I am trying to get the following output until a certain condition is met.
test_1.jpg
test_2.jpg
..
test_50.jpg
The solution (if you could remotely call it that) that I have is
fileCount = 0
while (os.path.exists(dstPath)):
fileCount += 1
parts = os.path.splitext(dstPath)
dstPath = "%s_%d%s" % (parts[0], fileCount, parts[1])
however...this produces the following output.
test_1.jpg
test_1_2.jpg
test_1_2_3.jpg
.....etc
The Question: How do I get change the number in its current place (without appending numbers to the end)?
Ps. I'm using this for a file renaming tool.
UPDATE: Using various ideas below, i've discovered a loop that works
dstPathfmt = "%s_%d%s"
parts = os.path.splitext(dstPath)
fileCount = 0
while (os.path.exists(dstPath)):
fileCount += 1
dstPath = parts[0]+"_%d"%fileCount+parts[1]
It's probably easiest to keep dstPath something like "test_%d.jpg", and just pass it a varying count:
dstPath = "test_%d.jpg"
i = 1
while os.path.exists(dstPath % i):
i += 1
dstPath = dstPath % i # Final name
Print out the value of parts[0] each time you go round the loop ... I think you may be surprised,
It seems as though your condition os.path.exists(dstPath) is matching the same renamed file multiple times. So for example, it renames test.jpg to test_1.jpg; then renames test_1.jpg to test_1_2.jpg, etc.
for j in range(1,10):
print("test_{0}.jpg".format(j))
enter image description here
Update for Python v3.6+ - using formatted string literals:
for n in range(1,51):
print(f'test_{n}')