How to write and read to a file in python? - python

Below is what my code looks like so far:
restart = 'y'
while (True):
sentence = input("What is your sentence?: ")
sentence_split = sentence.split()
sentence2 = [0]
print(sentence)
for count, i in enumerate(sentence_split):
if sentence_split.count(i) < 2:
sentence2.append(max(sentence2) + 1)
else:
sentence2.append(sentence_split.index(i) +1)
sentence2.remove(0)
print(sentence2)
outfile = open("testing.txt", "wt")
outfile.write(sentence)
outfile.close()
print (outfile)
restart = input("would you like restart the programme y/n?").lower()
if (restart == "n"):
print ("programme terminated")
break
elif (restart == "y"):
pass
else:
print ("Please enter y or n")
I need to know what to do so that my programme opens a file, saves the sentence entered and the numbers that recreate the sentence and then be able print the file. (im guessing this is the read part). As you can probably tell, i know nothing about reading and writing to files, so please write your answer so a noob can understand. Also the one part of the code that is related to files is a complete stab in the dark and taken from different websites so don't think that i have knowledge on this.

Basically, you create a file object by opening it and then do read or write operation
To read a line from a file
#open("filename","mode")
outfile = open("testing.txt", "r")
outfile.readline(sentence)
To read all lines from file
for line in fileobject:
print(line, end='')
To write a file using python
outfile = open("testing.txt", "w")
outfile.write(sentence)

to put it simple, to read a file in python, you need to "open" the file in read mode:
f = open("testing.txt", "r")
The second argument "r" signifies that we open the file to read. After having the file object "f" the content of the file can be accessed by:
content = f.read()
To write a file in python, you need to "open" the file in write mode ("w") or append mode ("a"). If you choose write mode, the old content in the file is lost. If you choose append mode, the new content will be written at the end of the file:
f = open("testing.txt", "w")
To write a string s to that file, we use the write command:
f.write(s)
In your case, it would probably something like:
outfile = open("testing.txt", "a")
outfile.write(sentence)
outfile.close()
readfile = open("testing.txt", "r")
print (readfile.read())
readfile.close()
I would recommend follow the official documentation as pointed out by cricket_007 : https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Related

Python reading text files

Please help I need python to compare text line(s) to words like this.
with open('textfile', 'r') as f:
contents = f.readlines()
print(f_contents)
if f_contents=="a":
print("text")
I also would need it to, read a certain line, and compare that line. But when I run this program it does not do anything no error messages, nor does it print text. Also
How do you get python to write in just line 1? When I try to do it for some reason, it combines both words together can someone help thank you!
what is f_contents it's supposed to be just print(contents)after reading in each line and storing it to contents. Hope that helps :)
An example of reading a file content:
with open("criticaldocuments.txt", "r") as f:
for line in f:
print(line)
#prints all the lines in this file
#allows the user to iterate over the file line by line
OR what you want is something like this using readlines():
with open("criticaldocuments.txt", "r") as f:
contents = f.readlines()
#readlines() will store each and every line into var contents
if contents == None:
print("No lines were stored, file execution failed most likely")
elif contents == "Password is Password":
print("We cracked it")
else:
print(contents)
# this returns all the lines if no matches
Note:
contents = f.readlines()
Can be done like this too:
for line in f.readlines():
#this eliminates the ambiguity of what 'contents' is doing
#and you could work through the rest of the code the same way except
#replace the contents with 'line'.

Unable to read file in python in w+ mode

I'm new to Python, and I am currently learning file operations. I am unable to read from a file, that I just wrote into. I'm using w+ mode.
Also please tell me, what I'm doing wrong in the
textbuffer = str("%r\n %r\n %r\n" % input(), input(), input())
which is commented.
Below is the code snippet:
filename = '/home/ranadeep/PycharmProjects/HelloWorld/ex15_sample.txt'
target = open(filename,'w+')
target.truncate()
print("Input the 3 lines: ")
textbuffer = "Just a demo text input"
#textbuffer = str("%r\n %r\n %r\n" % input(), input(), input())
target.write(textbuffer)
# read not working in w+ mode
print(target.read())
target.close()
# read only mode
updated_target = open(filename,'r')
print(updated_target.read())
with open(file_name,"w+") as f:
f.write("I love programming and i love python ")
f.seek(0) #move cursor to the start of the file
data=f.read()
print(data)
When you write to the file, the line you begin reading from only occurs after the line you wrote to. For this to work, you need to reset the "head" back to the beginning of the file.
target.write("blah")
# This is new
target.seek(0)
print target.read()
target.close()

How can I create a function that will allow me to edit a .txt file in python?

I'm trying to create a very simple function that will let me edit a file that I've already written using Python 3.5. My writing function works just fine, but I'm including it just in case it matters. It looks like this:
def typer():
print("")
print("Start typing to begin.")
typercommand = input(" ")
saveAs = input("Save file as: ")
with open(saveAs, 'w') as f:
f.write(typercommand)
if saveAs == (""):
commandLine()
commandLine()
My editing function looks like this:
def edit():
file = input("Which file do you want to edit? ")
with open(file, 'a') as f:
for line in f:
print(line)
I then call the function using my command line function like this:
def commandLine():
command = input("~$: ")
if command == ("edit"):
edit()
I don't get any errors but nothing else happens, either (I'm just redirected to my base command line). And by that I mean that I call the function and then, on the line directly beneath it, it get the prompt for the command line I made for the program (~$). What is wrong with my code and what could I do to remedy it?
If you want to read from and write to a file you have to open it with mode 'r+', 'w+' or 'a+'.
Note that 'w+' truncates the file, so you will probably need 'r+' or 'a+', see the doc
Something like:
def edit():
file = input("Which file do you want to edit? ")
with open(file, 'r+') as f:
for line in f:
print(line)
# here you can write to file
...
EDITED: indentation error
In your edit function, you are just printingat the standard output every line, but you are not writing anything.
def edit():
file = input("Which file do you want to edit? ")
with open(file, 'w+') as f:
filetext = ""
for line in f:
filetext += line
# do stuff with filetext
...
# then write the file
f.write(filetext)

Python: Example 16 Learn the hard way

I did example 16 and decided to keep adding to it. I wanted after rewriting the contents to be able to read it right after.
from sys import argv
script, file = argv
print "Do you want to erase the contents of %r?" % file
print "If yes hit RETURN, or CTRL-C to abort."
raw_input()
target = open(file, 'w')
target.truncate()
print "Now you can type new text to the file one line at a time."
line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")
print "The data will now be written to the file."
target.write(line1)
target.write('\n')
target.write(line2)
target.write('\n')
target.write(line3)
target.write('\n')
print "Data has been added to the file."
new_data = open(target)
print new_data.read()
After running it when I get to this point I get the syntax error need string to buffer, file found. I know from the beginning the file was opened in 'w' (write mode) so I also tried this:
new_data = open(target, 'r')
print new_data.read()
If you'd like to both read and write a file, use the appropriate mode, such as 'w+', which is similar to 'w' but also allows reading. I would also recommend the with context manager so you don't have to worry about closing the file. You don't need truncate(), either, as explained in this question.
with open(file, 'w+') as target:
# ...your code...
# new_data = open(target) # no need for this
target.seek(0) # this "rewinds" the file
print target.read()
The answer is in the error message, you are trying to pass a file into open() function whereas the first parameter should be a string - a file-name/path-to-file.
This suppose to work:
new_data = open(file, "r")
print new_data
It is more preferred to use the "open resource as" syntax since it automatically flushes and closes resources which you need to do after writing to a file before you can read from it (without seek-ing to the beginning of the file).
print "Do you want to erase the contents of %r?" % file
print "If yes hit RETURN, or CTRL-C to abort."
raw_input()
with open(file, 'w+') as target:
target.truncate()
print "Now you can type new text to the file one line at a time."
line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")
print "The data will now be written to the file."
target.write(line1)
target.write('\n')
target.write(line2)
target.write('\n')
target.write(line3)
target.write('\n')
print "Data has been added to the file."
with open(file) as new_data:
print new_data.read()

How can I tell python to edit another python file?

Right now, I have file.py and it prints the word "Hello" into text.txt.
f = open("text.txt")
f.write("Hello")
f.close()
I want to do the same thing, but I want to print the word "Hello" into a Python file. Say I wanted to do something like this:
f = open("list.py")
f.write("a = 1")
f.close
When I opened the file list.py, would it have a variable a with a value 1? How would I go about doing this?
If you want to append a new line to the end of a file
with open("file.py", "a") as f:
f.write("\na = 1")
If you want to write a line to the beginning of a file try creating a new one
with open("file.py") as f:
lines = f.readlines()
with open("file.py", "w") as f:
lines.insert(0, "a = 1")
f.write("\n".join(lines))
with open("list.py","a") as f:
f.write("a=1")
This is simple as you see. You have to open that file in write and read mode (a). Also with open() method is safier and more clear.
Example:
with open("list.py","a") as f:
f.write("a=1")
f.write("\nprint(a+1)")
list.py
a=1
print(a+1)
Output from list.py:
>>>
2
>>>
As you see, there is a variable in list.py called a equal to 1.
I would recommend you specify opening mode, when you are opening a file for reading, writing, etc. For example:
for reading:
with open('afile.txt', 'r') as f: # 'r' is a reading mode
text = f.read()
for writing:
with open('afile.txt', 'w') as f: # 'w' is a writing mode
f.write("Some text")
If you are opening a file with 'w' (writing) mode, old file content will be removed. To avoid that appending mode exists:
with open('afile.txt', 'a') as f: # 'a' as an appending mode
f.write("additional text")
For more information, please, read documentation.

Categories

Resources