How to fix error trying to find user files in Python? - python

I made this script to copy this file to any user's Documents folder:
import getpass
import os
user = getpass.getuser() #gets username
file = "try.py" #file to copy
new_file = "C:\\Users\\", user,"\\Documents\\try.py" #folder in which the file shoud copy
os.rename(file, new_file) #copy the file
The problem is, when I try to run it, IDLE show this error:
I don't really understand what it means. Please note that I am a beginner in Python.

new_file is not a concatenated string but a tuple.
Try using this for concatenation of strings
new_file = "C:\\Users\\" + user + "\\Documents\\try.py"

Related

Is there any way to create a folder with the same name as a variable and then put a JSON file on it in python?

Hi i am trying to create a folder that jas the same name of a variable and then write a JSON file inside that folder. Currently mi code looks something like this:
a = "name"
filename = "Configs/" + a + "/" + a
with open (filename, 'w') as f_obj:
json.dump(data, f_obj)
After that I get the following error:
FileNotFoundError : [Errno 2] no such file or directory : 'Configs/name/name'
When I try:
filename = "Configs/" + a
It works perfectly, I would appreciate any help, thanks in advance.
open can create new files to be written to, but it won't create new directories to put them in. The error you're getting is because the directory Configs/name doesn't exist - you need to create this first, then create the file inside of it. Here's one way to do this:
import json
from pathlib import Path
data = {} # whatever your data is
a = "name"
file_path = Path("Configs") / a / a
file_path.parent.mkdir(parents=True, exist_ok=True) # if these flags are right for you
file_path.write_text(json.dumps(data))

Use a raw_input to specify a specific file to create a copy of it's back up and change the file names of the back up and original file

I am working to set up a process that creates a new file from a backup file that is already in a folder. My program currently works, but I would like to eliminate as much of the user input as possible, so that all you have to do is enter the filename that just crashed on you and watch the program do the rest. I am fairly new at python and have been having trouble figuring out a way to get that initial raw_input to be the basis for the rest of the program to run off. I have uploaded the code that I have which currently does the job, so any tips that would help me make this code better would be much appreciated.
Thanks!
import os
import copy
import shutil
def copy_vrb():
#Creates a copy of a specific "Filename.vrb" which gets renamed to "Filename_COPY.vrb"
oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
newvrb=raw_input("Rename the new .vrb file to Filename_COPY")
shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
copy_vrb()
def file_rename():
# Takes original "Filename.vr" that crashed, and changes the filename to "Filename_BAD.vr".
oldname=raw_input("Enter the Filename.vr that you were working on before it crashed: ") # With file extension
newname=raw_input("Rename the file as Filename_BAD")
os.rename(oldname, newname + ".vr")
file_rename()
def rename_copy():
# Renames Filename_COPY.vrb to Filename_NEW.vr
oldname=raw_input("Enter the Filename_COPY.vrb: ") # With file extension
newname=raw_input("Rename to Filename_NEW: ") # Without file extension
os.rename(oldname, newname, +".vr")
rename_copy()
In my data folder that I would work out of, I have multiple pairs of files, (10001.vr(the file that would crash), and 10001.vrb(the backup that is created when I open the file in VR Mapping) What I want is to be able to input the specific file that crashed.
Create a copy of the 10001.vrb file ---> 10001_COPY.vrb
Change the 10001.vr file ---> 10001_BAD.vr
Lastly change the 10001_COPY.vrb file into the new usable file ---> 10001_NEW.vr
One way of doing this is you accept the name of file as a command line input instead of doing raw_input().
https://www.pythonforbeginners.com/system/python-sys-argv
import os
import copy
import shutil
def copy_vrb(oldvrb):
newvrb = os.path.splitext(oldvrb)[0] + "_COPY"
shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ")
copy_vrb(oldvrb)
And then you do the rest for the other functions.
You're on the right track. Just a matter of merging your functions - perhaps:
import os
import shutil
def recover_vrb():
vr_file = raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
vr_name = vr_file.split('.')[0]
vrb_file = vr_name + '.vrb'
moved_vr_file = vr_name + '_BAD.vr'
os.rename(vr_file, moved_vr_file)
shutil.copy(vrb_file, vr_file)

Write to any users desktop in Python

Im new to Python so apologies if this is a basic question.
I have successfully created an exe file that writes to my specific desktop directory, but I am struggling to find a way to write to any users desktop directory.
The idea being my exe file can be copied onto any user profile and work the same.
Here is my code:
file = open('C:\\Users\\user\\Desktop\\PC info.txt','w')
Could somebody help me adjust my code to work on any users desktop. Thank you in advance
You can get the username with the os module:
import os
username = os.getlogin() # Fetch username
file = open(f'C:\\Users\\{username}\\Desktop\\PC info.txt','w')
file.write('Hello desktop')
file.close()
You could use os.getlogin with an f-string to insert the username to the file path:
import os
with open(fr'C:\Users\{os.getlogin()}\Desktop\PC info.txt', 'w') as f:
# do something with f
But, a much better cleaner way nowadays would be to use pathlib:
import pathlib
with open(pathlib.Path.home() / "Desktop/PC info.txt", "w"):
# do something with f
Also, it's always advisable to use a context manager (with open(...) as f) to handle files, so that the filehandler gets closed even if an exception occurs.
If you are using Python3.5+, you can use the following to get the path to the current user's home directory:
import os
import sys
from pathlib import Path
def main():
home = str(Path.home())
path = os.path.join(home, "filename.txt")
with open(path, "w") as f:
f.write("HelloWorld")
if __name__ == '__main__':
main()
Is this what you are looking for?
username = "MrShaun"
filename = "C:\\Users\\{0}\\Desktop\\PC info.txt".format(username)
file = open(filename, 'w')
In this example, filename would be: "C:\Users\MrShaun\Desktop\PC info.txt"
Obviously, you would probably want to build a structure around it, for example asking the user for input of a username and assigning that to the variable username.
Read more about formatting strings in Python here

Python checking if files exist before writing

I have a file that contains .odt files and I would like to convert them to pdf. My current function works fine, the problem is that even if the file is already converted, the function converts it again, and I do not want to convert a file if it is already converted.
Is there a way to check if the name.odt and name.pdf files already exist?
import sys
import os
import comtypes.client
import glob
def convert():
for file in glob.glob("*.odt"): # Listing all files
wdFormatPDF = 17
in_file = os.path.abspath(file)
name, ext = os.path.splitext(file)
suffix = '.pdf'
os.path.join(name + suffix)
if not os.path.exists(name): # Pdf file doesn't exist
out_file = os.path.abspath(name)
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
print('the file ' + name +' has been converted')
else :
print('all the file are converted')
doc.Close()
word.Quit()
There are a few things that are not right with your code. Here's the minimal modifications I made to make it work:
import sys
import os
import win32com.client
import glob
def convert():
word = win32com.client.Dispatch('Word.Application')
for input_file in glob.glob("*.odt"): # Listing all files
wdFormatPDF = 17
in_file = os.path.abspath(input_file)
name, ext = os.path.splitext(input_file)
suffix = '.pdf'
name = name + suffix
if not os.path.exists(name): # Pdf file doesn't exist
out_file = os.path.abspath(name)
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
print('the file ' + name +' has been converted')
doc.Close()
else:
print('The file ' + name + ' already exists')
print('all the file are converted')
word.Quit()
os.chdir(r"C:\Users\evensf\Documents\Question-48733924\Source")
convert()
Here are my comments about my modifications:
For some reason I couldn't understand, I wasn't able to install the comtypes module. So I used the win32com module that comes with Python for Win32 (pywin32) extensions. I think it pretty similar.
I opened the Word connector object outside of the loop. You don't really need to open and close it every time you want to open a document. I couldn't make your code work without doing that and it should speedup the execution.
I changed your variable name from file to input_file because at one time the name was already assigned to something in Python and that could spell disaster, if I remember correctly. I think this isn't as relevant today, but it's always a good habit to have descriptive name for your variables.
Your code seemed to print that all the file are converted when it find an already existant PDF file. I couldn't understand why you would want to do that. So I have put a message when the PDF file has already been created and put your message outside the loop.
Since you seem to be working with files in the local directory. I added a command to change the working directory.
But we can go further and simplify your code:
import win32com.client
import pathlib
source_directory = pathlib.Path(r"C:\Users\evensf\Documents\Question-48733924\Source")
wdFormatPDF = 17
destination_suffix = '.pdf'
word_application = win32com.client.Dispatch('Word.Application')
for current_file in source_directory.glob("*.odt"): # Listing all files
absolute_current_file = current_file.resolve()
destination_name = absolute_current_file.with_suffix(destination_suffix)
if destination_name.exists():
print('The file', destination_name, 'already exists. Not converting.')
else:
current_document = word_application.Documents.Open(str(absolute_current_file))
current_document.SaveAs(str(destination_name), FileFormat=wdFormatPDF)
print('A file has been converted to', destination_name)
current_document.Close()
print('Finished converting files')
word_application.Quit()
I used the pathlib module which has a lot of provisions to simplify your code

Creating folders based on a list read from a text file

I have some code as follows:
from sys import argv
import os;
home_dir = '/home/joga'
script, dirlist = argv
mylist = open(dirlist, 'r')
for folder in mylist:
newFolder = home_dir+'/'+folder
print "Folder name " +newFolder
if not os.path.exists(newFolder):
os.makedirs(str(newFolder))
os.chdir(newFolder)
mylist.close()
The idea is to read a list of folders listed in text file, and create each of these folders if they don't already exist. I am getting the folders created, however some have strange names, for example a stray '?' appended to the folder name
How do I fix this?
Answering my own question
I added a folder = folder.strip() as the first line in my for loop. I guess it line-ending was creating the junk character.

Categories

Resources