How to write a file to the desktop in python? - python

When I make this code into an executable the function of writing a file works, but it writes to a random directory. I'm not sure how to get it to write to my desktop, like it did when it was a regular python file.
Here is my code,
def write():
print('Creating a new file')
name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt
try:
file = open(name,'w') # Trying to create a new file or open one
file.close()
except:
print('Something went wrong! Cannot tell what?')
sys.exit(0) # quit Python

You need to specify the path you want to save to. Furthermore, make use of os.path.join (documentation) to put the path and filename together. You can do something like this:
from os.path import join
def write():
print('Creating a new file')
path = "this/is/a/path/you/want/to/save/to"
name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt
try:
file = open(join(path, name),'w') # Trying to create a new file or open one
file.close()
except:
print('Something went wrong! Cannot tell what?')
sys.exit(0) # quit Python

It is not writing into a random directory. It is writing into current directory, that is the directory you run it from. If you want it to write to a particular directory like your desktop you either need to add the path to the file name or switch the current directory. The first is done with
name = os.path.join('C:\Users\YourUser\Desktop', name)
the second is done with
os.chdir('C:\Users\YourUser\Desktop')
Or whatever the path to your desktop is.

Related

How to create file .txt in a specific path of a directory

i want to create a text file in a specified directory. as shown below in the code, i am trying to create di.txt in pathToOutputDir but when i run the code, i find that di.txt is created as a yellow directory not a
as a text file that can be opened with notepad.
please let me know how to fix this code to create a .txt file.
Code :
def createOutPutDirectoryFor(self,directory):
pathToOutputDir = os.path.join(os.getcwd(), directory)
pathToOutputDir = os.path.join(pathToOutputDir, "di.txt")
It's difficult to tell what you are doing wrong, as you didn't include the part in your code that creates the file/directory. However, you're most likely using os.mkdir instead of creating a file.
You can do the following to create the file:
def createOutPutDirectoryFor(self,directory):
pathToOutputDir = os.path.join(os.getcwd(), directory)
pathToOutputDir = os.path.join(pathToOutputDir, "di.txt")
open(pathToOutputDir, 'a').close()
In your code, you create the path but don't actually create the file-
You can use the following to create the file:
open(pathToOutputDir, "x").close()
If you have fullpath of that directory then
def createOutPutDirectoryFor(self,directory):
pathToOutputDir = os.path.join(os.getcwd(), directory)
pathToOutputDir = os.path.join(pathToOutputDir, "di.txt")
try:
open(pathToOutputDir, 'a').close()
except FileNotFoundError:
open(pathToOutputDir, 'w').close()

Python - Input() multiple file paths at once and append in a list

I am writing a code to zipFile multiple files based on user's input.
For example, user type couple file paths such as C:\Users\AAA\BBB, C:\Users\AAA\CCC,... The program will back up all these files into one single new zipFile.
Right now I'm using a loop (the code from "While True") and it works. But this only allows us to enter one path each time. Is there a neat way that we can input all the path at once and add each of them in a list (fileList here)?
And as I just started Python and I wrote it based on "A Byte of Python", I feel my code is kind of lengthy... Please feel free to provide recommendation to improve it. Thank you.
import os,time,zipfile
def createZip():
# Define the file path to save the file
savePath=input('Enter file save path-->')
if len(savePath)==0:
print('No path is found. Backup ends.')
# Define the file to be saved
else:
assert os.path.exists(savePath),"File path does not exist. Backup fails." # assert expression1, expression2, equals to if not expression1, raise AssertionError(expression2)
fileList=[]
while True:
filePath=input('Enter files to save. Enter "Done" to end.-->')
if filePath=='Done':
break
else:
if len(filePath)==0:
print('No path is found. Please enter files to save.')
else:
assert os.path.exists(filePath),"File path does not exist. Backup fails."
fileList.append(filePath)
today=savePath+os.sep+time.strftime('%Y%m%d')
now=time.strftime('%H%M%S')
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
comment=input('Enter a comment -->')
if len(comment)==0:
target=today+os.sep+now+'.zip'
else:
target=today+os.sep+now+'_'+comment+'.zip'
newZip=zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) # 'w' means write only; 'r' means read only
for fName in fileList:
for root,dirs,files in os.walk(fName):
for file in files:
newZip.write(os.path.join(root,file))
newZip.close()
print('backup to',target)
createZip()
Its mostly easy. You can split the text the user enters, but you need to worry about files with spaces in their names. The shlex lets you split a line the same way a unix-like shell would, which gives you the rules you need.
import shlex
fileList = []
while True:
filePaths = input('Enter files to save. Enter "Done" to end.-->')
if filePaths.lower() == "done":
break
for filePath in shlex.split(filePaths):
if not os.path.exists(filePath):
print("'{}' not found".format(filePath))
else:
fileList.append(filePath)

Moving a file from one folder to another and back in Python

I'm relatively new to python and I'm working on a few projects. Say I'm running the script on partition D on Windows, so, for example, it's "D:/quarantine.py"
What I'm looking for right now is:
Taking a file from one folder (say, Desktop) and moving it to another folder (say, C:\Quarantine) - but I need to read both files and directories from the keyboard. The C:\Quarantine folder is created earlier with this code:
def create_quar(quar_folder):
try:
os.makedirs(quar_folder)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
dir_name = input("Enter the desired quarantine path: ")
if os.path.isdir(dir_name):
print ("Directory already existed.")
else:
print ("Directory created successfully!")
create_quar(dir_name)
Before moving the file, I need to store the file's previous location somehow. I was thinking of creating a .txt file in that C:\Quarantine folder.
If I ever change my mind, I call on a function that reads the .txt file I created earlier, and just moves the files back to the original folder. This, I have no idea how to implement.
I'm at a loss as to how to go about doing this. Was thinking of something like this for logging the path and moving the file:
path = input("Directory of file I need to move: ")
file = input("File name: ")
f = open(dir_name+"\log.txt",'w')
f.write(os.path.abspath(path+file))
shutil.move(path+file,dir_name+file)
dir_name is the variable I used earlier to read the Quarantine folder location, so I figured I could reuse it. As for the reading the log file and restoring, I have no idea.
Can anyone help?
You can use os.system() function by importing it from os. It will execute command in cmd/shell, but for the sub-process only.
I hope this is helpfull
Alright, so I managed to do this by myself in the end. In case anyone is interested you'll find samples of the code below. It's very rudimentary and can of course be optimized but it does work.
Main:
def Main():
dir_name = input("Enter the destination path: ")
if os.path.isdir(dir_name):
print ("Directory already existed.")
else:
print ("Directory created successfully!")
os.makedirs(dir_name)
choice = input("Would you like to (M)ove or (R)estore?: ")
if choice == 'M':
path = input("Directory of file you want moved: ")
file = input("Name of the file+extension: ")
file_path = path+'/'+file
move(file_path)
print ("Done.")
elif choice == 'R':
with open('quar_id.txt') as f:
quar_id = f.readline()
restore_from_quar(quar_id)
print ("Done.")
else:
print ("No valid option selected, closing...")
Move:
def move(filepath):
f = open('quar_id.txt','w')
f.write(path)
f.close()
os.chdir(dir_name)
shutil.move(file_path,dir_name+'/'+file)
Restore:
def restore(quar_id):
os.chdir(dir_name)
myfile = os.listdir(dir_name)
file = str(myfile)
file = file[2:-2]
shutil.move(file,quar_id+'/'+file)

Python3 Walking A Directory and Writing To Files In That Directory

I have created a script that writes the binary content of my files to other files in the same directory that end with a certain extension. When doing this however I have come onto an issue, when I open the file and save the new file in a folder, it creates a new file. I'll show an example. There is a folder, FOLDER1 with test.py inside, inside the folder is a folder called OPTION1 with the files, bye.sh and hello. When I try to execute test.py, my program sees the files bye.sh and hello(hello's binary data is being copied to bye.sh) in OPTION1 and reads it, but creates a new file in the FOLDER1 alongside test.py creating a new bye.sh in FOLDER1, how do I make it overwrite the bye.sh in OPTION1? Just mentioning, I am running Mac OS X.
Code here:
import os
class FileHandler:
#import all needed modules
def __init__(self):
import os
#Replaces second file with the binary data in file one
"""
Trys To Check If a File Exists
If It exists, it will open the file that will be copied in binary form and the output file in reading/writing binary form
If the input file doesnt exist it will tell the user, then exit the program
Once the files are open, it reads the input file binary and copies it to the output file
Then it checks to see if the two binaries match which they should if it all worked correctly, the program will then return true
The Files are then closed
If it failed to try it will tell the user the file was skipped
"""
def replaceBinary(self,file_in="",file_out=""):
try:
if(os.path.isfile(file_in)):
in_obj = open(file_in,"rb") #Opens The File That Will Be Copied
out_obj = open(file_out,"wb+") #Opens The File That Will Be Written To
object_data = in_obj.read()#Get Contents of In File
out_obj.write(object_data)# Write Contents of In File To Out File
print("SPECIAL FILE:"+file_out)
print(os.getcwd())
if out_obj.read() == in_obj.read():
print("Its the same...")
return True
print("Done Copying...")
else:
print("Usage: Enter an input file and output file...")
print(file_in+" Doesn't Exist...")
raise SystemExit
return False
in_obj.close()
out_obj.close()
except:
print("File, "+file_out+" was skipped.")
"""
Procedurally continues down an entire location and all its locations in a tree like manner
Then For each file found it checks if it matches of the extensions
It checks a file for the extensions and if it has one of them, it calls the replace binary function
"""
def WalkRoot(self,file1="",root_folder=""):
for root,dirs,files in os.walk(root_folder):
for f in files:
print(os.path.abspath(f))
array = [".exe",".cmd",".sh",".bat",".app",".lnk",".command",".out",".msi",".inf",".com",".bin"]
for extension in array:
if(f.endswith(extension)):
print("Match|\n"+os.path.abspath(f)+"\n")
self.replaceBinary(file1,os.path.abspath(f))
break #If The right extension is met skip rest of extensions and move to next file
print("Done...")
def main():
thing = FileHandler()
#path = os.path.join(os.getcwd())
path = input(str("Enter path:"))
thing.WalkRoot("Execs/hello","/Users/me/Documents/Test")
main()
Thanks!
The list of files returned by os.walk() does not include directory information. However, the dirpath (which you call root) is updated as you go through the list. Quoting the manual,
filenames is a list of the names of the non-directory files in dirpath. Note
that the names in the lists contain no path components. To get a full path
(which begins with top) to a file or directory in dirpath, do
os.path.join(dirpath, name).[1]
So, to get the correct, full path to the files within your top-level directory, try replacing
self.replaceBinary(file1,os.path.abspath(f))
with
self.replaceBinary(file1, os.path.join(root, f))
[1] https://docs.python.org/3.5/library/os.html#os.walk

Creating a python file in a local directory

Okay so I'm basically writing a program that creates text files except I want them created in a folder that's in this same folder as the .py file is that possibly? how do I do it?
using python 3.3
To find the the directory that the script is in:
import os
path_to_script = os.path.dirname(os.path.abspath(__file__))
Then you can use that for the name of your file:
my_filename = os.path.join(path_to_script, "my_file.txt")
with open(my_filename, "w") as handle:
print("Hello world!", file=handle)
use open:
open("folder_name/myfile.txt","w").close() #if just want to create an empty file
If you want to create a file and then do something with it, then it's better to use with statement:
with open("folder_name/myfile.txt","w") as f:
#do something with f

Categories

Resources