Executable file from Python script can't write to the file - python-3.x

I have a python code that write some outputs to the defined output file in text. In PyCharm, my script works without any problem but when i convert my xx.py to the .exe file by using pyinstaller, exe file can't write to the output file which is already in the same path.
To write the outputs i use this code:
fg = open('input.src')
output_file = open("output.obj", "w")
for line in fg:
**do something**
output_file = open("output.obj", "a")
output_file.write("[" + str(hex(memory_location)) + "]" + " " + output + "\n")
I also tried the xx.py without PyCharm, with console, and the script work fine.

when i convert it to the .exe file ...
It's not clear what conversion process you're referring to.
Definitely PyCharm is running a standard python interpreter as a child process.
It sounds like you may be running cython or other unusual language environment in your problem case.
You wrote:
output_file = open("output.obj", "w")
...
output_file = open("output.obj", "a")
You chose not to use the with idiom.
More importantly, you chose not to output_file.close() before re-opening.
Your combination of language interpreter + filesystem may require a close before a subsequent open.

Thanks to #mypetlion, the problem was caused by the encoding of the input file which was ANSI. It need to change into UTF-8.

Related

Code creates new .txt file in one .py but not in another .py

I'm writing a code which creates a new .txt file to which I will add data later on.
For testing and debugging I wrote it in another .py file and it's working. However when i copy the code to my main file it's not working anymore but it's not giving me an error either.
culturename_raw = str("filename123")
def create_rawfile():
outfile = open(culturename_raw, "a")
outfile.write("\n" + "text that I'm adding" + "\n")
outfile.close()
print("rawfile created")
create_rawfile()
When I run this code in my test .py it's creating a file with the name, writes the text und prints "rawfile created".
When I run this code in my main .py there is no error code and even prints "rawfile created" but there is no text file created.
I'm using Python 3.8 and PyCharm Community 2020.2 if that matters.
Try changing culturename_raw = str("filename123") to culturename_raw = str("filename123.txt"). You have to have the '.txt' extension.

Facing a strange "phantom filesystem" issue in Python

I first noticed this problem a bit ago when I posted this thread. Essentially, I'm getting a very strange issue where Python "sees" files that don't actually exist in my file browser when working with files.
As in, if I open a file with an absolute path, modify and print the contents of it through Python, it will print exactly what it's supposed to. But when I try to open the same file through the same absolute path on my Windows file browser, the file is not updated with my modifications.
I experienced a similar issue recently as well - renaming files. Here's a simple script I wrote to replace all spaces in filenames with underscores.
rename.py:
import os
i = 0
path = "E:/sample_path/"
for filename in os.listdir(path):
src = path + filename
dst = path + filename.replace(" ", "_")
os.rename(src, dst)
i += 1
print(str(i) + " files processed.")
Upon doing some prints in Python, I can see that all the files in the directory are being renamed correctly but it just wasn't correctly updating when I actually viewed the directory. Both in the file browser and in using the dir command. Same with creating new files in Python, they exist in the eyes of Python, but they are nowhere to be found in Windows, even with hidden files being visible and all.
Now for the interesting part: This script works if I open the python editor in cmd and import it. So I know it's all correct, no syntax errors or anything - it's just a strange error occurring with Python.
For example, if I go into command prompt and type python rename.py it won't return any errors and will even output the correct results - x files processed. but it will not actually modify any "real" files.
But if I go into command prompt and type python to bring up the cmd editor, then type import rename it gives the correct output and updates all the files correctly. So for the time being this workaround helps, but it's a very strange issue and I have yet to see anyone else encounter it. It's almost like Python creates a temporary duplicate of the filesystem and is not completing it's sync back to Windows.
I've tried reinstalling Python several times, both x64 and x86 verisons and nothing has fixed it so far.
EDIT: Here's a simplified example illustrating my issue.
write.py:
f = open("newfile.txt", "w+")
f.write("hello new file")
f.close()
read.py:
f = open("newfile.txt", "r")
for l in f.readlines():
print(l)
If I run write.py, no errors are returned. But also no file named newfile.txt is visible in my current working directory. However, if I run read.py it prints hello new file. So clearly both of these are accessing the same invisible file somewhere.

python - automatically launch a text file created in the program

I did the search but i couldn't find any help, apologies if i my question is duplicate.
i am writing the code with python 3.6 and in windows environment.in my code, i opened a text file, write the data and close the file.
self.fileName = 'file path'
self.log_file = open(self.fileName, 'w')
self.log_file.write('Write results')
self.lof_file.close()
Instead of the user goes to file path and click to open it, i want to launch the file automatically after python save it.
how do i do that? please help
EDIT:
os.startfile(filepath=self.fileName)
command is working fine, but its opening with default program which is Notepad, how to open the file with specific program, for example, Notepad++
If you know the command line way of doing it, you can use the os module as follows:
import os
self.file = 'file path'
self.log_file = open(self.fileName, 'w')
self.log_file.write('Write results')
self.lof_file.close()
os.system('gedit <file_path>') # for ubuntu, gedit is generally present
For Windows, you can use:
import os
os.startfile('C:\\Users\\RandomUser\\Documents\\test.txt')
Check this answer for more details: https://stackoverflow.com/a/15055133/9332801

How to convert Balsamiq mockups to text strings txt with Python34 script on Windows XP

I've been trying to run these scripts https://github.com/balsamiq/mockups-strings-extractor within XP. I'm getting errors per this screenshot https://www.dropbox.com/s/rlbqp1iytkwvq3m/Screenshot%202014-05-30%2011.57.48.png
Also I tried CD into my test directory and although a text output file is generated it is empty and I still get these errors https://www.dropbox.com/s/odjfbr97e5i4gnn/Screenshot%202014-05-30%2012.09.31.png
Is anybody running Balsamiq on windows able to make this work ?
1) From the looks of the first error pic you included, you were trying to execute a Windows Shell command inside of a Python Interpreter. If you've still got the window open, type quit() before attempting your command again.
2) Your script was written for Python 2.x. If you're using Python 3.x, you'll need to add parentheses to the print lines in the script file and change urllib to urllib.parse. I made the changes below:
import os
import glob
import re
import urllib.parse
for infile in glob.glob( os.path.join(".", '*.bmml') ):
print("STRINGS FOUND IN " + infile)
print("===========================================================")
f = open (infile,"r")
data = f.read()
p = re.compile("<text>(.*?)</text>")
textStrings = p.findall(data)
print(urllib.parse.unquote('\n'.join(textStrings))+"\n")
f.close()
Hope this helps.

Testing python programs without using python shell

I would like to easily test my python programs without constantly using the python shell since each time the program is modified you have to quit, re-enter the python shell and import the program again. I am using a 2012 Macbook pro with OSX. I have the following code:
import sys
def read_strings(filename):
with open(filename) as file:
return file.read().split('>')[1:0]
file1 = sys.argv[1]
filename = read_strings(file1)
Essentially I would like to read into and split a txt file containing:
id1>id2>id3>id4
I am entering this into my command line:
pal-nat184-102-127:python_stuff ceb$ python3 program.py string.txt
However when I try the sys.argv approach on the command line my program returns nothing. Is this a good approach to testing code, could anyone point me in the correct direction?
This is what I would like to happen:
pal-nat184-102-127:python_stuff ceb$ python3 program.py string.txt
['id1', 'id2', 'id3', 'id4']
Let's take this a piece at a time:
However when I try the sys.argv approach on the command line my
program returns nothing
The final result of your program is that it writes a string into the variable filename. It's a little strange to have a program "return" a value. Generally, you want a program to print it's something out or save something to a file. I'm guessing it would ease your debugging if you modified your program by adding,
print (filename)
at the end: you'd be able to see the result of your program.
could anyone point me in the correct direction?
One other debugging note: It can be useful to write your .py files so that they can be run both independently at the command line or in a python shell. How you've currently structured your code, this will work semi-poorly. (Starting a shell and then importing your file will cause an error because sys.argv[1] isn't defined.)
A solution to this is to change your the bottom section of your code as follows:
if __name__ == '__main__':
file1 = sys.argv[1]
filename = read_strings(file1)
The if guard at the top says, "If running as a standalone script, then run what's below me. If you imported me from some place else, then do not execute what's below me."
Feel free to follow up below if I misinterpreted your question.
You never do anything with the result of read_strings. Try:
print(read_strings(file1))

Resources