I have the following python-script, which open a text-file:
import sys
file = r"D:/...../text.txt"
with open (file,"r") as infile:
text = infile.read()
print (text)
If I want to run this script on another computer, i have to change the path (the same text-file "text.txt" will be saved on the other computer). Is there any way to let my script search the computer for the text-file without writing the path in the script?
Thank you.
Have you tried putting it in a relative directory, e.g.:
import sys
file = r"text.txt"
with open (file,"r") as infile:
text = infile.read()
print (text)
Just keeping the text file in the same directory as the small program.
You can use glob to get the result you want, but the glob will return a list of files, you may need to adapt your code.
Using a GUI for "choose file"
import sys
from Tkinter import *
import tkFileDialog
master = Tk()
master.withdraw() #hiding tkinter window
file_path = tkFileDialog.askopenfilename(title="Open file", filetypes=[("txt file",".txt"),("All files",".*")])
with open (file_path,"r") as infile:
text = infile.read()
print (text)
Related
The below works as expected:
import shutil
source = "c:\\mydir\myfile.txt"
dest_dir = "c:\\newdir"
shutil.move(source,dest_dir)
However, this also succeeds. I would want this to fail.
import shutil
source = "c:\\mydir"
dest_dir = "c:\\newdir"
shutil.move(source,dest_dir)
Any way to ensure that only a file is moved. Both Windows and Unix would be great. If not, Unix at least.
You could use pathlib's purepath.suffix to determine if a path points to a file or a directory, like so:
import pathlib
def points_to_file(path) -> bool:
if pathlib.PurePath(path).suffix:
return True
else:
return False
pathtodir = r'C:\Users\username'
pathtofile = r'C:\Users\username\filename.extension'
print (f'Does "{pathtodir}" point to a file? {points_to_file(pathtodir)}')
# Result -> Does "C:\Users\username" point to a file? False
print (f'Does "{pathtofile}" point to a file? {points_to_file(pathtofile)}')
# Result -> Does "C:\Users\username\filename.extension" point to a file? True
You can define a custom function to ensure that source is a file (with os.path.isfile function):
from os import path
def move_file(src, dst):
if not path.isfile(src):
raise IsADirectoryError('Source is not a file')
shutil.move(src, dst)
import os ,fnmatch
import os.path
import os
file_dir= '/home/deeghayu/Desktop/mec_sim/up_folder'
file_type = ['*.py']
for root, dirs,files in os.walk( file_dir ):
for extension in ( tuple(file_type) ):
for filename in fnmatch.filter(files, extension):
filepath = os.path.join(root, filename)
if os.path.isfile( filepath ):
print(filename , 'executing...');
exec(open('/home/deeghayu/Desktop/mec_sim/up_folder/{}'.format(filename)).read())
else:
print('Execution failure!!!')
Hello everyone I am working on this code which execute a python file using a python code. I need to save my output of the code as a text file. Here I have shown my code. Can any one give me a solution how do I save my output into a text file?
Piggybacking off of the original answer since they are close but it isn't a best practice to open and close files that way.
It's better to use a context manager instead of saying f = open() since the context manager will handle closing the resource for you regardless of whether your code succeeds or not.
You use it like,
with open("file.txt","w+") as f:
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
try
Open file
f= open("file.txt","w+")
Insert data into file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Close the file
f.close()
Currently, this code works. It creates a text file named SerialNumber that saves in pictures. The problem is I can't seem to work out how to get it to work on any computer. So for example, if I remove \users\Jarvis from the file path it no longer finds its way to pictures. I'm trying to get it to work no matter who is logged in.
import os
Save_Path='C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt'
with open(Save_Path, 'w') as f:
f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\Jarvis\\Pictures\\SerialNumber.txt"')))
I've tried to set it as:
\users\Admin
\users%UserProfile%
\users\user
but that returns
FileNotFoundError: [Errno 2] No such file or directory:
import os
from pathlib import Path
Save_Path= 'C:\\Users\\Pictures\\SerialNumber.txt'
path = Path.home() / "Pictures\SerialNumber.txt"
with open(path, 'w') as f:
f.write(str(os.system('start cmd /k "wmic bios get serialnumber >C:\\Users\\%UserProfile%\\Pictures\\SerialNumber.txt"')))
With Subprocess and replace I was able to print to python just the serial number
import subprocess
SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
print(result.replace("SerialNumber", ""))
Okay after some help, and research, This is the final code. It uses a subprocess that will output to python>CMD. I then used re (lines 7 and 8) to .strip and re.sub removing everything that wasn't actually the serial number. I installed pyperclip to copy
import subprocess
import pyperclip
import re
import os
SerialNumber = 'wmic bios get serialnumber'
result = subprocess.getoutput(SerialNumber)
SerialResult = (result.strip("SerialNumber"))
print(re.sub("[^a-zA-Z0-9]+", "", SerialResult))
pyperclip.copy(re.sub("[^a-zA-Z0-9]+", "", SerialResult))
I wrote a function that is supposed to look for all the file with the extension chosen, in the selected directory. Actually, it runs but it doesn't return anything.
I am trying to keep things simple/stupid, since I am just at the beginning of my journey in Python
Below, I reported the code.
Thanks for your help!
THIS ONE RUNS, BUT RETURNS AN EMPTY LIST
import fnmatch
import glob
def lookfor(dir, ext):
direct = glob.glob(dir)
files = []
for file in direct:
if fnmatch.fnmatch(file, ext):
files.append(file)
return files
print(lookfor('C:/Users/nameuser/where/folder/', '*.docx'))
THIS ONE WORKS PROPERLY, BUT ONLY FOR .docx FILE, AS WRITTEN INSIDE THE FUNCT
import fnmatch
import glob
def lookfor(dir):
direct = glob.glob(dir)
files = []
for file in direct:
if fnmatch.fnmatch(file, '*.docx'):
files.append(file)
return files
print(lookfor('C:/Users/nameuser/where/folder/*.docx'))
i have a method that opens a file and then calls another method,
which opens up a window (i am using tkinter) that asks the user whether he would like to open another file. Now, each time a file gets opened i want to add the filename to a list, but in my case when i look at the result the list only contains the last selected filename.
I will include my stripped down code:
def fileopening(self):
from tkinter.dialog import askopenfilename
import os.path
self.inputfilenamelist = []
self.fileopenname.set(askopenfilename(filetypes = [("binary files","*.bin*"),("all files","*.*")]))
basename = os.path.basename(self.fileopenname.get())
self.inputfilenamelist.append(basename)
self.askforanotherinput()
def askforanotherinput(self):
inputwindow = tk.Toplevel(root)
inputwindow.title("Inputselection")
inputwindow.minsize(400,200)
asklabel = tk.Label(inputwindow,text="Select another inputfile?")
asklabel.pack()
answeryesbutton = tk.Button(inputwindow,text="Yes")
answeryesbutton.pack()
answeryesbutton["command"]=lambda:[inputwindow.destroy(),self.fileopening()]
answernobutton = tk.Button(inputwindow,text="No")
answernobutton.pack()
answernobutton["command"]=lambda:[inputwindow.destroy(),self.fileopeningcounter.set(0)]
Can anyone help me ? The thing is i need this "method-calling-loop" since i am using the opened files in further data conversion as a whole.