Editing text files in python - python-3.x

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')

Related

loop doesn't break up when receiving data from client even i wrote break

Hi everyone I decided to create a program that transfer files between client and server, but the problem is the loop won't break its looks like he's still waiting for data to receive, even I wrote (if not data: break)
I received the file successfully, but it's not back to the outer loop any help and thank you.
while True:
###server side
cmd = input("enter msg command :")
client_socket.send(cmd.encode())
if cmd.startswith("download"):
filename = cmd.strip("download ")
with open(filename, 'wb') as f:
print("Downloading file...")
while True:
data = client_socket.recv(4096)
if not data:
break
f.write(data)
print("Successfully downloaded")`
#####clientside
while True:
command = s.recv(1024)
command = command.decode()
if command.startswith("download"):
print("True\n")
filename = command.strip("download ")
with open(filename,'rb') as f:
print("file sending.....")
while True:
data = f.read(4096)
if not data:
break
s.sendall(data)
print("file has sent")

Python: What exceptions should I handle in this pieces of code?

Not sure how or what exceptions should I take into account.
I have the following piece of code that handles default files to pass to the program if not specified.
if len(sys.argv)==1:
fileName = "file1.txt"
else:
fileName = sys.argv[1]
The other part of code is when opening the file:
with open(fileName) as file:
for line in file:
words = line.split(';')
....
....
....
You should use FileNotFoundError.
Example below taking user input:
yourPath = input('Enter your path')
try:
with open(yourPath) as fl:
for i in fl:
print(i)
except FileNotFoundError:
print('Please enter correct path')
OR you can use IOError:
yourPath = input('Enter your path')
try:
with open(yourPath) as fl:
for i in fl:
print(i)
except IOError:
print('Please enter correct path')
OR if you are not sure about just use except:
yourPath = input('Enter your path')
try:
with open(yourPath) as fl:
for i in fl:
print(i)
except:
print('Please enter correct path')

Says it can't find the txt file

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()

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()

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