This answer was solved by doing print (file.read())
I have a project called 'PyDOS'. I recently discovered that you can read and write files in Python, I implemented this and the writing bit worked. But when trying the read part, it gives a syntax. The code that's messing up the reading part is:
print file.read
This is the code with the first error:
def textviewer():
print ("Text Viewer.")
file_name = input("Enter a text file to view: ")
file = open(file_name, "r")
print file.read #This returns 'Syntax Error' when pressing F5
input("Press enter to close")
def edit(): #However, the writing function works just fine.
os.system('cls' if os.name == 'nt' else 'clear')
print ("EDIT")
print ("-------------")
print ("Note: Naming this current document the same as a different document will replace the other document with this one.")
filename = input("Plese enter a file name.")
file = open(filename, "w")
print ("Now, Write 5 lines.")
line1 = input()
line2 = input()
line3 = input()
file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.close()
print ("File saved!")
time.sleep(3)
It returns syntax error, I tried file.read() but instead showed:
<built-in method read of _io.TextIOWrapper object at 0x10ada08>
<built-in method read of _io.TextIOWrapper object at 0x10ada08>
That's the string representation of a function. What you want isn't the function itself, but rather to call the function.
In other words, you want file.read() instead of file.read.
Also, in Python 3.x, print is a function, not a keyword, so you want print(file.read()), not print file.read().
Incidentally, file is the name of a built-in function (albeit a deprecated one), so you should use a different variable name.
Related
I have a predefined function that I am currently running to check if a file a input is correct. I wish to open this file in my function with the with" operator. This is what I currently have:
def open_file():
'''Checks if the file is correct.'''
grab_file = True #Creates initial variable that checks if file is correct
while grab_file == True: #Loop initiates the check if true
txt = input("Enter a file name: ") #Asks for file input
try:
f = open(txt) #Tries to open the file
return f #File returned as output
grab_file = False #Stops the loop
except: #File is invalid, prompts for retry
print("Error. Please try again.")
def main():
'''Main function that runs through file and does delta calculations.'''
with open(open_file()) as f:
f.readline()
print_headers()
pass
Not sure what exactly is the issue, thanks! Note the second portion of the code is in its own main function and is not part of the open_file function.
The code gives me an error when I try to run the following:
f.readline()
date = f.readline()
print_headers()
This is the error I am getting, the code after the with open statement are just a simple readline(
"TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper"
Your error is a fairly easy fix:
just replace the
with open(open_file()) as f:
with
with open_file() as f:
because you've already opened the file and returned the open file in the open_file() function.
However the print_headers() function doesn't exist in standard python 3.x so I'm not quite sure if this is your own function or a different mistake.
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()
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
I have the following code:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open('targetfile' , 'w')
print "What do we write in this file?"
targetfilefound.write("hello this is working!")
targetfilefound.close()
The script I'm creating should be able to write to a file that the user defines via raw_input. The above could be faulty at core, open to suggestions.
Judging by the stuff the script is printing you probably want the user to input what should be printed to the file so:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
Note: This method will create the new file if it does not exist. If you want to check whether the file exists you can use the os module, something like this:
import os
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
if os.path.isfile(targetfile) == True:
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "File does not exist, do you want to create it? (Y/n)"
action = raw_input('> ')
if action == 'Y' or action == 'y':
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "No action taken"
As pointed out by others, remove the quotes from target file as you have assigned it already to a variable.
But actually instead of writing as code you can use the with open as given below
with open('somefile.txt', 'a') as the_file:
the_file.write('hello this is working!\n')
In the above case, you don't need to do any exception handling while processing the file. When-ever an error occurs the file cursor object is automatically closed and we dont need to explicitly close it. Even it writing to file it success, it will automatically close the file pointer reference.
Explanation of efficient use of with from Pershing Programming blog
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()