is there a way to open files without using QFileDialog.getOpenFileName parameter? The thing is, I have a some buttons that upon clicking them, a notepad will pop up in which you can type anything into the notepad. Then, you can save whatever you wrote in that notepad as a text file. What I want to do is, if I click the button again, I will reopen the file that I had previously edited via the notepad and can continue typing where I left off. However, I don't want to use getOpenFileName. Would it be possible to open a file without using this functionality? Below is my attempt but my if statement keeps evaluating to be false. If anyone could help that would be great. Thanks!
#Testing if the file already exists
if(os.path.exists("~/Desktop/" +self.fileName + ".txt")):
f = open(self.fileName + ".txt", 'r')
filedata = f.read()
self.text.setText(filedata)
f.close()
#Opens a new notepad if there wasn't a previous fileconstructed
else:
self.textBox = textBoxWindow(self.fileName)
self.textBox.show()
If you are on Winsows (you said the word Notepad), you can use the subprocess module to open any file with whatever program currently associated with the file type as follows:
import subprocess
self.filename = r'C:\test.txt'
subprocess.call(['start', self.filename], shell=True)
But the shell=True argument is kinda dangerous, especially of the filename comes as an input.
you can use the webbrowser module too, though not supported use of it I guess:
import webbrowser
webbrowser.open(self.filename)
Related
I am trying to check if a file exists, if it does exist, I want to check if it is open by trying to rename it. The except block is trying to close the open file using os.close. When I try to close the file I get "TypeError: an integer is required".
import os
filepath = "C:\Users\oneilp6\Desktop"
file1 = filepath + "\\HelpFile.docx"
file2 = filepath + "\\HelpFile2.docx"
if os.path.exists(file1):
try:
os.rename(file1,file2)
except:
os.close(file1)
Anyone have any thoughts or ideas? I am trying to close a word document that is actually open in MS Word. Is there a way to do that?
You are checking whether the file is open by a different application on your computer. If it is, there isn't much this program can do about it. You don't get to close other program's files. You could potentially hunt down that program and kill it, but even that isn't easy. There are some suggestions at https://serverfault.com/questions/1966/how-do-you-find-what-process-is-holding-a-file-open-in-windows.
There is no file opened in the except. so no need to call os.close().
https://docs.python.org/2/library/os.html#os.rename
os.close() This function is intended for low-level I/O and must be
applied to a file descriptor as returned by os.open() or pipe(). To
close a “file object” returned by the built-in function open() or by
popen() or fdopen(), use its close() method.
I would like to import some data from a .txt file.
Right now I am doing it like so:
filename = "C:/results/results.txt"
file = open(filename, 'r')
lines = file.readlines()
file.close()
I wondering if there is way to have some dialog box, which will allow picking the right .txt file file, instead of supplying filename variable. Like this:
Is it possible to get this dialog box without some custom python UI module (like tkinter or similar)? Is it possible to get it through System.Windows.Forms for example?
I am using python 2.7.
Thank you for the reply
In this case the path is to use the ironpython, link
for some reason the readline() function in my following code seems to print nothing.
fileName = input()
fileName += ".txt"
fileA = open(fileName, 'a+')
print("Opened", fileA.name)
line = fileA.readline()
print(line)
fileA.close()
I'm using PyCharm, and I've been attempting to access 'file.txt' which is located inside my only PyCharm project folder. It contains the following:
Opened file!!
I have no idea what is wrong, and I can't find any relevant information for my problem whatsoever. Any help is appreciated.
Because you opened the file in a+ mode, the file pointer starts at the end of the file. After all, that is where you would normally append text.
If you want to read from the top, you need to place fileA.seek(0) just before you call readline:
fileA.seek(0)
line = fileA.readline()
Doing so sets the pointer to the top of the file.
Note: After reading the comments, it appears that you only need to do this if you are running a Windows machine. Those using a *nix system should not have this problem.
I am creating a tempFile and then adding text to it by opening it with an editor(so that user can enter his message), and then save it to read the text from save NamedTemporaryFile.
with tempfile.NamedTemporaryFile(delete=False) as f:
f.close()
if subprocess.call([editor.split(" ")[0], f.name]) != 0:
raise IOError("{} exited with code {}.".format(editor.split(" ")[0], rc))
with open(f.name) as temp_file:
temp_file.seek(0)
for line in temp_file.readlines():
print line
But every time it is coming out to be blank. why is it so ?
If you are using SublimeText as the editor, you will need to pass in the -w or --wait argument to make sure that the Python program waits until you actually close SublimeText again.
Otherwise, you would just start to edit the file, and immediately try to read its contents which at that point are empty.
You could also verify that, by putting in a print before reading the file.
E.g.:
editor = ['/path/to/sublime_text', '-w']
with tempfile.NamedTemporaryFile(delete=False) as f:
f.close()
if subprocess.call(editor + [f.name]) != 0:
raise IOError()
# read file…
Here's a solution without editor interaction since I don't have enough information to mimic your editor setup.
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as f:
f.close()
with open(f.name, f.mode) as fnew:
# Replace with editor interaction
fnew.write('test')
fnew.seek(0)
for line in fnew.readlines():
print line
At least on my system and version (2.7.2), I had to make these changes to allow the file object to be properly reopened and interacted with, and it builds correctly in Sublime. f.name is the temporary file path, and f.mode is the mode used by the already closed file (in this case it should default to 'w+b').
I am writing a script to log into a switch, write the config to a file, and then rename the file. I have the parts working separately. The issue is that I cannot figure out how to get all parts with in the same function so that I can use the function on a list of devices. I get a file not open for reading in the for 'line in f' statement. when as far as i can see the file is still open.
I have tried writing a function to rename the file that works on its own, but not when in this script with the other parts.
I have another script that i wrote that has the rename portion outside of the function which works, but will not work to rename the file if multiple hosts are called with the Exscript 'quickstart' module.
Thanks for any help,
from Exscript.util.start import quickstart
import os
import datetime
import time
time = datetime.datetime.now().strftime("%d-%m-%Y")
tm = 'c:/test/tmp.txt'
def do_something(job, host, conn):
f = open(tm, 'w+') #opens File with read and write permissions
conn.execute('term len 0')
conn.execute('sh run')
f.write(conn.response)
conn.execute('quit')
#this is the part where the error comes
for line in f:
if "hostname" in line:
host = line.strip()
test = 'c:/test/' + host[9:] + 'on' + time + '.txt'
os.rename(tm, test)
quickstart('ssh://x.x.x.x', do_something)
According to the manual, mode w+ truncates (removes all the content from) the file. If you want to open the file for both reading and writing without destroying its contents, use mode r+ or a+.
::edit:: Note, I'm not sure how this works on Windows.
You have to test the file pointer at the beginning of the file using f.seek(0). Or first write to the file then close it then reopen it for reading. But you dont need a file at all - you can as well work on a local variable.