Python Forum
Having issues with open,write,read
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Having issues with open,write,read
#1
import sys
import os
import time

from pathlib import Path


my_file = Path("database.txt")

print("I HIGHLY RECOMMEND USING DATABASE.TXT AS I HAVE NOT REWROTE THE SCRIPT TO ALWAYS USE THIS VALUE")
f = "database.txt"
try:
    file = open(f, 'r')
except IOError:
    file = open(f, 'w')

if my_file.is_file():
    
#    f= open("database.txt","w+")
    f= open("database.txt","r+")
    
    infilename = "database.txt"
    with open(infilename, "r") as f:
        line_list = f.readlines()
    
#    f = f.readlines()
    f.close()
    found = False
    f= open("database.txt","r+")
    for line in f:
        if str("users") in line:
            print ("Found it")
            print ("Beginning database edit/user add")
            print ("You will be requested for input soon")
            usernamenew = input("New DB username: ")
            passwordnew = input("New DB password: ")
            f= open("database.txt","a+")
            f.write("UN: {}".format(usernamenew))
            f.write("UP: {}".format(passwordnew))
            found = True

    if not found:
        print("Not found")
#     else:
        f = open('database.txt', 'a')
        f.write(str("NUN: root 1")+"\n")
        f.close()
        print("\nCreating database")
        time.sleep(3)
        print(".")
        time.sleep(1)
        print("..")
        time.sleep(1)
        print("...")
        time.sleep(1)
        print(".")
        time.sleep(1)
        time.sleep(5)
        print("\nCreating user")
        print(".")
        time.sleep(1)
        print("..")
        time.sleep(1)
        print("...")
        time.sleep(1)
        print(".")
        time.sleep(6)
        confirm = input("\nAre you sure you wish to write changes? Y/N: ")
        if confirm == str("Y") or str("y"):
            print("\nWriting changes NOW")
            f= open("database.txt","w+")
            f.close
            for i in range(1):
                f= open("database.txt","a+")
                f.write("users \r\n")
                f.write("NUN: root %d\r\n" % (i+1))
                f.write("NUP: root %d\r\n" % (i+1))
                f.close
            for i in range(1):
                f= open("database.txt","w+")
                f.write("users \r\n")
                f.write("NUN: root %d\r\n" % (i+1))
                f.write("NUP: root %d\r\n" % (i+1))
                f.close        
        else:
            print("You have aborted the database creation")
            print("The following script may not run. This is due to no/invalid database installation")
The above script works perfectly, but this: 
try:
    file = open(f, 'r')
except IOError:
    file = open(f, 'w')

if my_file.is_file():
    
#    f= open("database.txt","w+")
    f= open("database.txt","r+")
    
    infilename = "database.txt"
    with open(infilename, "r") as f:
        line_list = f.readlines()
    
#    f = f.readlines()
    f.close()
    found = False
    f= open("database.txt","r+")
    for line in f:
        if str("users") in line:
            print ("Found it")
            print ("Beginning database edit/user add")
            print ("You will be requested for input soon")
            usernamenew = input("New DB username: ")
            passwordnew = input("New DB password: ")
            f= open("database.txt","a+")
            f.write("UN: {}".format(usernamenew))
            f.write("UP: {}".format(passwordnew))
            found = True
Does not. It takes the values, but then does not write them to the file, the rest of the script works fine.
Any ideas?

(The time stuff is just because I wanted some sort of loading thing. Didnt have to work. Got bored. And I get NO ERROR when running the script.)
Reply
#2
You must specify a file name as a parameter to open - open(f, 'r'). What does "f" contain?

In line 6 - if my_file.is_file():. To check if something is a file

if os.path.isfile(file_name):
    # do
Also, you are opening one file twice with different flags. Line 9, line 12.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(Mar-10-2017, 09:22 PM)wavic Wrote: You must specify a file name as a parameter to open - open(f, 'r'). What does "f" contain?

In line 6 - if my_file.is_file():. To check if something is a file

if os.path.isfile(file_name):
    # do
Also, you are opening one file twice with different flags. Line 9, line 12.

Thanks for the reply, but I got nothing, didn't work. The file did not update.

EDIT: In fact when I removed line 9 it didnt detect the file and on line 12 I get an IO error, because python automatically closes the file.
Reply
#4
How did you modify the code? Is there an error message? What you expect to happen but it does not? You can't just say "it doesn't work". I have to look at my crystal bow. If I remember where I left it
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
(Mar-10-2017, 09:33 PM)wavic Wrote: How did you modify the code?

When I removed line 9 it didnt detect the file and on line 12 I get an IO error, because python automatically closes the file.
Reply
#6
Yes, because in line 16 you are closing a file which is not open.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
(Mar-10-2017, 09:40 PM)wavic Wrote: Yes, because in line 16 you are closing a file which is not open.
I commented it out before I ran it before. Forgot to say that. Sorry.

EDIT: Realised I commented the wrong line. Commented the right line out, ran again. No IO error, but nothing is written to the file.
Reply
#8
Did you write this code?

Again, in line 18 you are opening the file to read it. Without closing it, in line 26 you are opening it again to appending to it. You have to close this one too.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
(Mar-10-2017, 09:50 PM)wavic Wrote: Did you write this code?

Again, in line 18 you are opening the file to read it. Without closing it, in line 26 you are opening it again to appending to it. You have to close this one too.

Yes, I wrote this code. Python is not my expertise. Im more of a HTML kinda guy, a teacher decided to get me into python. So here I am making a useless script to modify a text file, for another python script that reads that text file.
Because
I have nothing to do in my spare time. So im not the 'greatest' and I make very buggy software.
Also, I do not need to close from line 26 as python closes it as it is the end of a block.
If I put f.close at the start of the 
if str("users") in line:
block then python will start going mental saying that it cant run anything due to the block being based of a value that depends on the file being open.
I did try commenting out line 26 and running it. Still nothing written.
I may give up and redo the whole thing. In theory it SHOULD work, but doesnt.
Reply
#10
You should remove code that does nothing to increase clarity.

I guess that code that do something starts on line 18. You are opening same file twice (not a problem), under same handle (again not a problem, but very confusing) and you are opening both of them in write mode (or append). That could be problem - they are closed automatically, but their content might depend on order of closing. You should open it on line 18 just for reading - you dont need more. And explicitly close your "second" file after line 28. Even better would be to use with for that file.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,409 Nov-09-2023, 10:56 AM
Last Post: mg24
Question Special Characters read-write Prisonfeed 1 606 Sep-17-2023, 08:26 PM
Last Post: Gribouillis
  How do I read and write a binary file in Python? blackears 6 6,410 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Read text file, modify it then write back Pavel_47 5 1,577 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  how to read txt file, and write into excel with multiply sheet jacklee26 14 9,842 Jan-21-2023, 06:57 AM
Last Post: jacklee26
  Read JSON via API and write to SQL database TecInfo 5 2,178 Aug-09-2022, 04:44 PM
Last Post: TecInfo
  Write and read back data Aggie64 6 1,852 Apr-18-2022, 03:23 PM
Last Post: bowlofred
  UART Serial Read & Write to MP3 Player Doesn't Work bill_z 15 5,747 Jul-17-2021, 04:19 PM
Last Post: bill_z
  Open and read multiple text files and match words kozaizsvemira 3 6,728 Jul-07-2021, 11:27 AM
Last Post: Larz60+
  Read and write active Excel file euras 4 3,468 Jun-29-2021, 11:16 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020