Python script not writing to txt file - python

I have a Python script that runs properly on my laptop, but when running on my raspberry pi, the following code does not seem to be working properly. Specifically, "TextFile.txt" is not being updated and/or saved.
openfile = open('/PATH/TextFile.txt','w')
for line in lines:
if line.startswith(start):
openfile.write(keep+'\n')
print ("test 1")
else:
openfile.write(line)
print ("test 2")
openfile.close()
I am seeing "test 1" and "test 2" in my output, so I know that the code is being reached, paths are correct, etc
It may be due to a permissions problem. I am running the script from the terminal by using:
usr/bin/python PATH/script.py
Python is owned by "root" and script.py is owned by "Michael".

My first guess:
Does the file exist? If it does not exist then you cannot write to it. Try this to create the file if it does not exist: file = open('myfile.dat', 'w+')
Additionally manually opening and closing file handles is bad practice in python. The with statement handles the opening and closing of the resource automatically for you:
with open("myfile.dat", "w+") as f:
#doyourcalculations with the file object here
for line in f:
print line

All, thank you for your input. I was able to figure out that it was writing to the new file, but it was overwriting with the same text. The reason was because ".startswith" was returning false when I expected true. The misconception was due to the difference between how Windows and Unix treat new line characters (/n /r).

Since your code is running, there should be a file somewhere.
You call "PATH/script.py", but there is "/PATH/TextFile.txt" in your program. Is the slash before PATH a mistake? Have you checked the path in your program is really where you are looking for the output file?

Related

python file error while execution

I am creating a simple python file in unix, just to open and write some test in it, but getting error while execution. Using Python 2.4.3
file = open(“testfile.txt”, “w”)
file.write(“This is a test”)
file.write(“To add more lines.”)
file.close()
Error:
./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `file = open(“testfile.txt”, “w”)'
I believe you are using curly quotes “” (e.g. from Microsoft Word, etc..) rather than actual single and double quote chars '' "".
Make sure you are using a regular text editor, not a rich text editor. That's the problem.
The problem is that “ is not a valid quote in Python. Try copying and pasting this code into your file/terminal and you should then realise the difference.
file = open("testfile.txt", "w")
file.write("This is a test")
file.write("To add more lines.")
file.close()
In addition to the "smart" quotes that need to be plain ASCII " characters you need a "shebang" line as the first line of the script. Otherwise it is likely to be treated as a shell script and handed to /bin/sh for execution. You should insert this as the first line of the file:
#!/usr/bin/env python
Or run it via python ./x.py.
I think quotes are the problem.
can you try a content manager
with open('testfile.txt', 'w') as output_file:
output_file.write("Your Text Here")
use of context managers is to properly manage resources. In fact, that's the reason we use a context manager . The act of opening a file consumes a resource (called a file descriptor), and this resource is limited by your OS. Similarly writing.
That is to say, there are a maximum number of files a process can have open at one time.

Python - script outputs wrong .xml file

I have a python script that makes a .xml file. I am running this script on my server. And it runs fine and at the end of the script I put the generated file on my server like this.
output_path = "/path_to_my_loication/"
ofname = "name_of_file.xml"
output_file = output_path + ofname
open(output_file, "w").write(str(BeautifulSoup(get_xml(menu_url_list[0][1]))))
and is just part of making the file, pretty sure its irrelevant to this. So run the script on my server and it outputs my file, and I can see it, but the url is not correct instead of it being.
myserver/path_to_my_loication/name_of_file.xml
it is
myserver/path_to_my_loication/%0d%0dname_of_file.xml
This is being added %0d%0d before the file name I am not sure how to fix this, and when I print my file name just before I write the file, the characters are not there? How can I get rid of this/ why does this happen.
When I just run the script on my laptop the file name does not contain theses characters. Is it a server side issues that I should contact my serve provider about?
Thanks for the help.
Okay AIG cause when I printed for my server I saw this, I though enter was just some weird thing
How can I get rid of the enters?
Here is full code
https://gist.github.com/spennyf/de3349252695cecd4e6c

builtins.permissionerror, but no file is there?

I'm trying to do inplace editing of a file using the fileinput module, but it doesn't seem to want to work.
The code I'm using:
for line in fileinput.FileInput(complaint_db, inplace=True, backup=(complaint_db + ".backup")):
print("Started replacement")
if line == myline:
pass
else:
print(line)
The backup argument is modified because I thought it might fix the error, it didn't. The file does not exist before I run this command (I have checked a hundred times) nor does it after. I'm creating the file in my home directory so there should be no error.
Here is the full error:
builtins.PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'c:\\Users\\Cody\\Documents\\ComplaintManagement\\complaints.dbc:\\Users\\Cody\\Documents\\ComplaintManagement\\complaints.db.backup'
I guess another question is, how do I check if the original complaints.db is open somewhere in the file without knowing where it might be open. If so, can I universally close it at will from any point in the code?
I can't do a f.close because f won't be defined at this point in the code. I tried os.close(complaint_db) (complaint_db is a universal variable holding the location of the db). It won't work because it requires an int, so I'm kind of lost now.
I fixed this by using a different form of changing the database. Instead of fileinput, I changed it to the following code:
from shutil import move
def RemoveClaim(self, myline):
ocdb = open(complaint_db, 'r')
ncdb = open(complaint_db + "2", 'w')
for line in ocdb:
if line == myline:
pass
else:
ncdb.write(line)
ocdb.close()
ncdb.close()
move(complaint_db + "2", complaint_db)
This seems to have solved my issues, as it works, and I have no errors.

Safe way to read directory in Python

try:
directoryListing = os.listdir(inputDirectory)
#other code goes here, it iterates through the list of files in the directory
except WindowsError as winErr:
print("Directory error: " + str((winErr)))
This works fine, and I have tested that it doesnt choke and die when the directory doesn't exist, but I was reading in a Python book that I should be using "with" when opening files. Is there a preferred way to do what I am doing?
You are perfectly fine. The os.listdir function does not open files, so ultimately you are alright. You would use the with statement when reading a text file or similar.
an example of a with statement:
with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
lines=file.readlines() #read all the lines in the file
#when the code executed in the with statement is done, the file is automatically closed, which is why most people use this (no need for .close()).
What you are doing is fine. With is indeed the preferred way for opening files, but listdir is perfectly acceptable for just reading the directory.

write in file is not complete without quitting the IDLE(Python GUI)

I want to write something in a file.
for example,
fo=open('C:\\Python\\readline_test.txt','a')
for i in range(3):
st='abc'+'\n'
fo.write(st)
fo.close
then I open this python file in IDLE, and click "Run Module".
There is no error message but I find the writing is not complete if I didn't quit IDLE.
How can I complete the file writing without quitting the IDLE?
Thanks.
(I use Python 2.6.2 on Windows XP.)
Maybe a typo, but it should be:
fo.close()
Then it should work.
Alternative you can use the with statement syntax (better example):
with open('C:\\Python\\readline_test.txt','a') as fo:
for i in range(3):
fo.write('abc'+'\n')
The file is automatically closed when leaving the with block.
(Instead of 'abc'+'\n', just write 'abc\n')
You can try using
fo.flush()
and mayby
os.fsync()
after writing to file object to ensure that all file operations are flushed to disk.

Categories

Resources