I want to read from a file with a python application. Here is my source code.
MyApplication.py:
if __name__ == '__main__':
fin = open("/absolute/path/to/file.txt", "r")
fin.readline()
fin.close()
setup.py:
# Copied and pasted it from their docs
from setuptools import setup
setup(
app=["MyApplication.py"],
setup_requires=["py2app"],
)
Then I try to run python setup.py py2app and everything goes smoothly, however when I open the app a popup appears saying "MyApplication Error".
Is there a way for me to solve this or at least get more information about what's happening?
EDIT FOR MORE CLARITY:
The line that is causing problems is fin.readline(). Also, writing to files works, and reading a file that the app itself has created doesn't generate errors. This code, for example, works.
if __name__ == '__main__':
fout = open("/absolute/path/to/newfile.txt", "a+")
fout.write("Test\n")
fout.close()
fin = open("/absolute/path/to/newfile.txt", "r")
line = fin.readline()
fin.close()
fout = open("/absolute/path/to/newfile.txt", "a+")
fout.write("Line read: " + line)
fout.close()
The output file will show:
Test
Line read: Test
I found this hint veeery useful:
“right click -> Show Packages -> Resources -> Mac OS”, and execute your app directly do help, because it shows specific errors on the console
Source: http://uxcrepe.com
It might help you a lot, as it shows you typical python errors you are already familiar with!
Enjoy!
It was the encoding, because of course it was. Just open the file like this.
fin = open("/absolute/path/to/file.txt", "r", encoding="utf-8")
Related
What I need to do is to write some messages on a .txt file, close it and send it to a server. This happens in a infinite loop, so the code should look more or less like this:
from requests_toolbelt.multipart.encoder import MultipartEncoder
num = 0
while True:
num += 1
filename = f"example{num}.txt"
with open(filename, "w") as f:
f.write("Hello")
f.close()
mp_encoder = MultipartEncoder(
fields={
'file': ("file", open(filename, 'rb'), 'text/plain')
}
)
r = requests.post("my_url/save_file", data=mp_encoder, headers=my_headers)
time.sleep(10)
The post works if the file is created manually inside my working directory, but if I try to create it and write on it through code, I receive this response message:
500 - Internal Server Error
System.IO.IOException: Unexpected end of Stream, the content may have already been read by another component.
I don't see the file appearing in the project window of PyCharm...I even used time.sleep(10) because at first, I thought it could be a time-related problem, but I didn't solve the problem. In fact, the file appears in my working directory only when I stop the code, so it seems the file is held by the program even after I explicitly called f.close(): I know the with function should take care of closing files, but it didn't look like that so I tried to add a close() to understand if that was the problem (spoiler: it was not)
I solved the problem by using another file
with open(filename, "r") as firstfile, open("new.txt", "a+") as secondfile:
secondfile.write(firstfile.read())
with open(filename, 'w'):
pass
r = requests.post("my_url/save_file", data=mp_encoder, headers=my_headers)
if r.status_code == requests.codes.ok:
os.remove("new.txt")
else:
print("File not saved")
I make a copy of the file, empty the original file to save space and send the copy to the server (and then delete the copy). Looks like the problem was that the original file was held open by the Python logging module
Firstly, can you change open(f, 'rb') to open("example.txt", 'rb'). In open, you should be passing file name not a closed file pointer.
Also, you can use os.path.abspath to show the location to know where file is written.
import os
os.path.abspath('.')
Third point, when you are using with context manager to open a file, you don't close the file. The context manger supposed to do it.
with open("example.txt", "w") as f:
f.write("Hello")
I am trying to load a JSON file into python with the following code:
import json
def find_case(tag):
with open("C:\\Users\\brend\\Documents\\File Organiser\\Files\\.filepaths\\" + tag + ".json", "r") as f:
filepaths_dict = json.load(f)
This seems to work fine withing PyCharm but crashes immediately on the above line. Can anyone tell me what is causing this and how to fix it?
I'm trying to create a .txt file with some data, and I want the file name to be the current time. But when I run my code it creates an empty file instead, without any file-type. Here is the code in question:
filename = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H:%M')
with open('%s.txt' % filename, 'w') as open_file:
# writing to file
It seems to ignore the ".txt" part because if i write the code like this it works just fine:
with open('filename.txt', 'w') as open_file:
It runs fine on my machine (Ubuntu 16.04 and python 3.5)
import datetime
import time
filename = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d_%H:%M')
with open('%s.txt' % filename, 'w') as file:
file.write('code written')
please provide more info
And yes i am getting .txt in my file name
In windows, you cant use : in the filename. It stops the creation of the file when it reaches the colon.
this is my code to open a file and get the text from it :
f = open("C:/Users/muthaharsh/Documents/Harsh/News
Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-
Mint.txt","r+")
text = f.readlines()
print(text)
but i keep getting the error :
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt'
What code do i write to be able to do this ?
Thanks in advance ...
It's the whitespace in the path to file. Either use
r"C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt"
or remove the whitespace in the filepath.
If you are running the code on windows add r before your filepath string.
Another way is that you can provide your input file as system arguments.
import sys
file_name = sys.argv[1]
with open(file_name, 'r') as f1:
file_text = f1.read()
print(file_text)
eg: python program for reading the file
you can run the code considering script is saved as readFile.py:
D:\Programs>python readFile.py D:\test.txt
output: This is a sample file
Here is the text
ftp.cwd("TXNnIGZvbGRlcg==/")
file = open('msg.txt', 'rb')
file.storbinary('STOR msg.txt', file)
file.close
So just a quick answer I need... the code shows a msg being saved in the base64 folder in the FTP server, however in earlier code, I've already said:
if name != "":
ftp.mkd(name)
ftp.cwd(name)
So it's already navigated somewhere, but I need help on finding the command on how to go back a directory.
something like
ftp.goback()
Or something.
I believe you can try something like this.
ftp.cwd("TXNnIGZvbGRlcg==/")
file = open('msg.txt', 'rb')
ftp.storbinary('STOR msg.txt', file)
file.close()
ftp.cwd("../")