Scan a directory and transfer files - python

I think that's easy but my script doesn't work. I think it's gonna be easier if I show you what I want: I want a script (in python) which does that:
I have a directory like:
boite_noire/
....helloworld/
....test1.txt/
....test2.txt/
And after running the script I would like something like:
boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt
and if I add an other test1.txt like:
boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt
....test1.txt
The next time I run the script:
boite_noire/
helloworld/
....test1/
........test1_date.txt
........test1_date.txt
....test2/
........test2_date.txt
I wrote this script :
But os.walk read files in directories and then create a directory named as the file, and I don't want that :(
Can someone help me please?

You could loop through each file and move it into the correct directory. This will work on a linux system (not sure about Windows - maybe better to use the shutil.move command).
import os
import time
d = 'www/boite_noire'
date = time.strftime('%Y_%m_%d_%H_%M_%S')
filesAll = os.listdir(d)
filesValid= [i for i in filesAll if i[-4:]=='.txt']
for f in filesValid:
newName = f[:-4]+'_'+date+'.txt'
try:
os.mkdir('{0}/{1}'.format(d, f[:-4]))
except:
print 'Directory {0}/{1} already exists'.format(d, f[:-4])
os.system('mv {0}/{1} {0}/{2}/{3}'.format(d, f, f[:-4], newName))
This is what the code is doing:
Find all file in a specified directory
Check the extension is .txt
For each valid file:
Create a new name by appending the date/time
Create the directory if it exists
move the file into the directory (changing the name as it is moved)

Related

Selenium how to save screenshot to specific directory in Python

I would like to take a screenshot for my selenium driver and save it to a specific directory. Right now, I can run:
driver.save_screenshot('1.png')
and it saves the screenshot within the same directory as my python script. However, I would like to save it within a subdirectory of my script.
I tried the following for each attempt, I have no idea where the screenshot was saved on my machine:
path = os.path.join(os.getcwd(), 'Screenshots', '1.png')
driver.save_screenshot(path)
driver.save_screenshot('./Screenshots/1.png')
driver.save_screenshot('Screenshots/1.png')
Here's a kinda hacky way, but it ought to work for your end result...
driver.save_screenshot('1.png')
os.system("mv 1.png /directory/you/want/")
You might need to use the absolute path for your file and/or directory in the command above, not 100% sure on that.
You can parse the file path you want to the save_screenshot function.
As your doing this already a good thing to check is that os.getcwd is the same as the location of the script (may be different if your calling it from somewhere else) and that the directory exists, this can be created via os.makedirs.
import os
from os import path
file_dir = path.join(os.getcwd(), "screenshots")
os.makedirs(file_dir, exist_ok=True)
file_path = path.join(file_dir, "screenshot_one.png")
driver.save_screenshot(file_path)
If os.getcwd is not the right location, the following will get the directory of the current script..
from os import path
file_dir = path.dirname(path.realpath(__file__))

Python processing 3 why is current working directory different sometimes?

I am getting this error sometimes when working on mac in Processing for Python. Seemingly for no reason, sometimes the current working directory becomes what you see in the image while other times it is the working directory of the folder the pyde file is in as it should be.
Any ideas on why this is occurring?
It's to avoid problems like these that I always try to use absolute paths. I would suggest you try something like this for file paths:
import os
# This will be the path to your .py file
FILE_PATH = os.path.dirname(os.path.abspath(__file__))
# This will be the path to your text file, if it is in the same directory as the .py
LEVELS_FILE_PATH = os.path.join(FILE_PATH, "levels.txt")
Then, instead of your current open statement you could have:
f = open(LEVELS_FILE_PATH, 'r')

Can i shorten a file location to the .py files location

first post here so sorry if it's hard to understand. Is it possible to shorten the directory in python to the location of the .py file?. For example, if I wanted to grab something from the directory "C:\Users\Person\Desktop\Code\Data\test.txt", and if the .py was located in the Code folder, could I shorten it to "\data\test.txt". I'm new to python so sorry if this is something really basic and I just didn't understand it correctly.
I forgot to add i plan to use this with multiple files, for example: "\data\test.txt" and \data\test2.txt
import os
CUR_FILE = os.path.abspath(__file__)
TARGET_FILE = "./data/test.txt"
print(os.path.join(CUR_FILE, TARGET_FILE))
With this, you can move around your Code directory anywhere and not have to worry about getting the full path to the file.
Also, you can run the script from anywhere and it will work (you don't have to move to Code's location to run the script.
You can import os and get current working directory ,this will give you the location of python file and then you can add the location of folder data and the file stored in that ,code is given below
import os
path=os.getcwd()
full_path1=path+"\data\test.txt"
full_path2=path+"\data\test2.txt"
print(full_path1)
print(full_path2)
I think this will work for your case and if it doesn't work then add a comment

How do I make the current folder path to work for my command

I'm new to Python and really want this command to work so I have been looking around on google but I still can't find any solution. I'm trying to make a script that deletes a folder inside the folder my Blender game are inside so i have been trying out those commands:
import shutil
from bge import logic
path = bge.logic.expandPath("//")
shutil.rmtree.path+("/killme") # remove dir and all contains
The Folder i want to delete is called "killme" and I know you can just do: shutil.rmtree(Path)
but I want the path to start at the folder that the game is in and not the full C:/programs/blabla/blabla/test/killme path.
Happy if someone could explain.
I think you are using shutil.rmtree command in wrong way. You may use the following.
shutil.rmtree(path+"/killme")
Look at the reference https://docs.python.org/3/library/shutil.html#shutil.rmtree
Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
Assuming that your current project directory is 'test'. Then, your code will look like the follwing:
import shutil
from bge import logic
path = os.getcwd() # C:/programs/blabla/blabla/test/
shutil.rmtree(path+"/killme") # remove dir and all contains
NOTE: It will fail if the files are read only in the folder.
Hope it helps!
What you could do is set a base path like
basePath = "/bla_bla/"
and then append the path and use something like:
shutil.rmtree(basePath+yourGamePath)
If you are executing the python as a standalone script that is inside the desired folder, you can do the following:
#!/usr/bin/env_python
import os
cwd = os.getcwd()
shutil.rmtree(cwd)
Hope my answer was helpful
The best thing you could do is use the os library.
Then with the os.path function you can list all the directories and filenames and hence can delete/modify the required folders while extractring the name of folders in the same way you want.
for root, dirnames, files in os.walk("issues"):
for name in dirnames:
for filename in files:
*what you want*

accessing sub directory in python

I'm trying to access a folder that is in the current directory in which I am writing my code. the folder I am currently in is cs113
I've tried to do
file2 = open("/cs113/studentstoires/Zorine.txt", "r)"
Would someone please tell me whey this doesn't work I've also tried to write the directory name like this:
open("/studentstories/Zorine.txt", "r")
Do I need to import sys and use sys.listdir or os.path? If so can you please give a quick little example how to do this? Thank you in advance.
If it's in the current directory, and it's the directory where you execute the script from, you should write the path without the / up front like so:
file2 = open("studentstories/Zorine.txt", "r")

Categories

Resources