-1

i just started learning file handling using pthon and tries this as a code but for some reason my readlines() function returns an empty list i have a name and password saved in the UsernameAndPassword.txt file

path1="C:/Users/om/UsernameAndPassword.txt"
f1=open(path1,'a+')
l1=f1.readlines()
print(l1)
def main():
    un=input("Enter Username: ")
    if un in l1:
        i1=l1.index()
        p1=l1[i1+1]
        pcheck1=input("Enter Password: ")
        if pcheck1==p1:
            print("Succesfully Logged In!")
            def main2():
                f2=input("Enter Path of file you want to Access or Path of file you want to create\n")
                if f2.exists()==True:
                    open(f2,'a+')
                    input1=input("Enter Text you want to write into the File(Enter Blank to stop and a space to leave a line)\n")
                    while True:
                        input2=input("\n")
                        if input2=="":
                            break
                        else:
                            f2.write(input1)
                            f2.write(input2)
                    input3=input("Do you want to Read the file?\n")
                    if input3=='Yes' or input3=='yes':
                        r1=f2.read()
                        print(r1)
                    else:
                        print("Do you want to access another file?")
                        input3=input("")
                        if input3=='yes' or 'Yes':
                            main2()
                        else:
                            print("Thank you for using this :)")
                else:
                    print("File Path Invalid!")
                    input4=input("Try Again?\n")
                    if input4=='yes' or 'Yes':
                        main2()
                    else:
                        print("Thank you for using this :)")
            main2()    
        else:
            print("Wrong Password")
            main()
    else:
        print("Wrong Username")
        input5=int(input("Sign up(Enter 1) or Try again(Enter 2)\n"))
        if input5==2:
            main()
        elif input5==1:
            inp6=input("Enter New Username: ")
            inp7=input("Enter Password: ")
            f1.write(inp6)
            f1.write(inp7)
            main()
        else:
            print("Invalid Input")
            print("Thank you for using this :)")
    f2.close()
f1.close()
main()
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • [How do I format my code blocks?](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) – mkrieger1 Apr 13 '22 at 13:29
  • 1
    What did you read about the "a+" file mode before you decided to use it? – mkrieger1 Apr 13 '22 at 13:31
  • 1
    Does this answer your question? [How to read from file opened in "a+" mode?](https://stackoverflow.com/questions/14639936/how-to-read-from-file-opened-in-a-mode) – mkrieger1 Apr 13 '22 at 13:32
  • Note that you won't be able to log in with this code anyway, as `if un in l1:` will never be true. `un`, as the result from `input()`, never contains a newline - but the lines read from the file will always end with a newline, except perhaps the very last line. – jasonharper Apr 13 '22 at 13:37

2 Answers2

0

a+ is a file mode which effectively means "able to append and read". In particular, since we're appending, it starts at the end of the file rather than the beginning. You can think of it as like a cursor in Notepad or your favorite text editor: When you open a file in r mode, the cursor starts at the beginning and has the whole file to read, but when you open in a mode, the cursor starts at the end of the file so that subsequent writes don't overwrite existing content.

In your case, since you're only ever reading from the file, just use the r mode.

f1 = open(path, 'r')

If you really need a+ (again, the snippet you've shown us doesn't, but your real requirements may differ), then you can manually seek to the beginning of the file to read.

f1 = open(path, 'a+')
f1.seek(0)
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0
class sth:
     def __init__(self, filepath):
        with open(filepath, 'r') as file:
            lines = file.readlines()
            self.comment = lines[0].strip()
            self.scale_factor = float(lines[1].strip())
            self.lattice_vectors = np.array([list(map(float, line.split())) for line in lines[2:5]])
            self.elements = lines[5].strip().split()
            self.num_atoms = list(map(int, lines[6].strip().split()))
            self.coordinate_type = lines[7].strip()
            self.direct_coordinates = np.loadtxt(filepath, skiprows=8)

    def volume(self):
        a1, a2, a3 = self.lattice_vectors
        return np.abs(np.dot(a1, np.cross(a2, a3))) * self.scale_factor**3

    def plot_structure(self):
        cartesian_coordinates = self.scale_factor * np.dot(self.direct_coordinates, self.lattice_vectors)
        colors = ['red', 'blue', 'green', 'orange', 'purple']
        start = 0
        for i, element in enumerate(self.elements):
       plt.scatter(cartesian_coordinates[start:start+self.num_atoms[i], 0],
                   cartesian_coordinates[start:start+self.num_atoms[i], 1],
                    label=element, color=colors[i])
        start += self.num_atoms[i]
    
plot
    def missing_atom_coordinates(self):
    cartesian_coordinates = self.scale_factor * np.dot(self.direct_coordinates, self.lattice_vectors)
    missing_atom_coord = np.mean(cartesian_coordinates[1:], axis=0)
    return missing_atom_coord

cr = crn('crn')
print(cr.numb_as)
print(":", cr.volume())
cr.plot_structure()
print("Ms:", cr.mac())
ffs
  • 1