Says it can't find the txt file - python-3.x

This is the code that I have. I'm just trying to get it to read and show what's in the file. Whenever I run it, it says that the file/directory can't be found? But my python and text files are in the same file..
I'm new to this so I'm not sure where I'm going wrong with it.
def main():
f = open("rules.txt", "r")
if f.mode == "r":
contents = f.read()
print(contents)
if __name__ == "__main__":
main()

Related

Editing text files in python

I'm trying to edit text files in real time, like this text box here, you can write and edit any word you want and then save it to the file, think nano for linux. Anyone know a way of doing this?
I have no idea how to start so I haven't tried anything.
Also something simple please doesn't need to be crazy efficient.
The reading and current writing part of the script look like this:
f = open('./PYOS/startMessage.txt', 'r')
start_message = f.read()
print(start_message)
f.close()
while True:
user_input = str(input('P:\> '))
command = user_input.lower()
if command == 'read':
filename = input('Filename: ')
try:
file = open(filename, 'r')
cont = file.read(filename)
print('File contents: ', cont)
except FileNotFoundError:
print('File not found please try again')
elif command == 'write':
filename = input('Filename: ')
try:
file = open(filename, 'w')
write = input('Write in file: ')
cont = file.read(filename)
print('You wrote: ', cont)
except FileNotFoundError:
print('File not found please try again')

Python 3 will not read appended data to file

I am trying to write binary data to a file. the program will check first if the file exists. If the file does not exist, the program will create the file and write data into it. While if it does exist the data will be appended to the file. Yet, when ever i try to read the file I cannot read the appanded data only the data written when the file was first created.
def getText(self):
self.readKey()
st = self.inBox.get('1.0', 'end')
fen = Fernet(self.readKey())
encrypted = fen.encrypt(st.encode())
return encrypted
def writeFile(self):
if (os.path.exists('data.txt') == False):
file = open('data.txt',mode='wb' )
file.write(self.getText())
file.close()
else:
file = open('data.txt',mode='ab' )
#sts = file.read()
file.write(self.getText())
file.close()
self.inBox.delete('1.0','end')
def openFile(self):
self.outBox.delete('1.0','end')
fen = Fernet(self.readKey())
try:
f = open("data.txt", mode='rb')
except:
alert_popup(self,'Error','No File Exists')
self.outBox.insert(tk.END, fen.decrypt(f.read()))
Use mode 'a'.
if (os.path.exists('data.txt') == False):
file = open('data.txt',mode='a' )
file.write(self.getText())
file.close()

How do I make my python program to write a new file

I am writing a program by which I can extract data from a file, and then based on some condition, I have to write that data to other files. These files do not exist and only the code will create these new files. I have tried every possible combination of print parameters but nothing is helping. The program seems to run fine with no error in IDLE but no new files are created. Can somebody give me a solution?
Here is my code:
try:
data= open('sketch.txt')
for x in data:
try:
(person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
man=[] # list to store person
other=[] #list to store sentence
if person=="Man":
man.append(sentence)
elif person=="Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
otherman_file=open("otherman_file.txt", "w")
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
2 problems
you should use
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
w+ - create file if it doesn't exist and open it in write mode
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file..
https://docs.python.org/2/library/functions.html
2.
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
if sketch.txt file do not exist then "man" and "other" will not initialized
and in the print method will throw another exception
try to run this script
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()

Using two kv files in one program error

I am quite new to OOP, and I am currently trying to create my first project using kivy. The program is currently stuck at the point of when I login I try and open a new kv file, but it will not open. Here is the python code:
window_widget = Builder.load_file("LiveScoringV104KVLoggedIn.kv")
class LoginScreen(Screen):
def checkLogin(self, username, password):
usernamesFile = open("dataUsernamesV104.txt", "r")
passwordsFile = open("dataPasswordsV104.txt", "r")
for line in usernamesFile.readlines():
for lineb in passwordsFile.readlines():
with open("dataprintedUsernameV104.txt", "w") as printedUsername:
printedUsername.write(username + "\n")
if line == username and lineb == password:
print("This is working")
return window_widget
else:
print("All wrong")
root_widget = Builder.load_file("LiveScoringV104KV.kv")
class StartupHome(App):
def build(self):
return root_widget
if __name__ == "__main__":
StartupHome().run()
when I login, which is correct because this is working is printed, window_widget is not called as it does not run the kv file, yet root_widget is called .How can I get the kv file to run like root_widget? (If you need the kv code just ask)

Creating a function to ask user for a file

I'm trying to make function which asks the user for a filename. If the file is not found, it will keep asking. This what I have please help..
def return_text_file(infile):
while infile:
try:
file = open(infile)
except IOError:
print("Could not find the file specified")
infile = input ("Enter the file name")
return open_infile
file_input = input ("Enter the file name")
return_text_file(file_input)
You can create a function (e.g. ask_file_name below) to get a valid answer from the user. It will repeat constantly until an existing name is given.
import os
path_str = '/home/userblabla/ProjectBlabla/'
def ask_file_name():
files_detected = os.listdir(path_str)
while True:
print('\nFiles:')
for file in files_detected:
print(file)
file_name_given = input('\nFile name?')
if file_name_given not in files_detected:
print("Could not find the file specified")
else:
print('Thanks friend.')
return file_name_given
my_file_name = ask_file_name()
with open(my_file_name, 'r') as opened_file:
# Do stuff on opened_file
......
with open() automatically closes the file, and it might be better if you use it instead of open().

Resources