Python raw_input for file writing - python

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

Related

Trying to search through multiple text files for a specific string. I then want the program to print out the text file that it found the string in

I am a beginner to Python have been trying to create a simple python menu. One of the options asks the user what user they want to search for. Each user will have a text file dedicated to them, and when the user types and searches for that user, it will search through a list of text files in a directory, and then it will print all of the user's details onto the program. I have managed to get my program to search through the text files to find the right user, but I am unsure of how to print the text file onto my program.
Code:
import os
from os import listdir
os.system("")
import glob
import os.path
menu()
option = int(input("\n" + "Enter your option: "))
while option !=0:
if option == 1:
dir_path = r'D:\My project'
for file in os.listdir(dir_path):
cur_path = os.path.join(dir_path, file)
if os.path.isfile(cur_path):
with open(cur_path, 'r') as file:
username = input("Enter a username: ")
if username in file.read():
print('user found')
#Here is where I want to print the contents of the text file that
#has been found
menu()
break
else:
print ("Invalid option")
I have tried to make the program print "username", "file" etc, but in doing so this only prevents the program from working, as it will think that anything I enter is an invalid option.
Any help would be really appreciated, thanks!
Try saving the file contents in a variable:
if os.path.isfile(cur_path):
with open(cur_path, 'r') as file:
contents = file.read()
username = input("Enter a username: ")
if username in contents:
After the first file.read(), the file object's position is at the end and nothing will be read in subsequent calls, unless you go back to the start with file.seek(0).
See Methods of File Objects for more details.
As an aside, pathlib might be a better fit than os.path.

How do I remove and then open a file for writing in python?

Here is some code.
sbfldr = input('Enter subfolder name: ')
try:
os.remove(os.path.join(sbfldr, 'Report.html'))
except:
print('Remove error. Please close the report file')
exit()
try:
fwrite = open(os.path.join(sbfldr, 'Report.html'),'a')
exit()
except:
print('Open error. Please close the report file')
exit()
The results I expect are
If an old version of 'Report.html' exists, then remove it.
Open a new 'Report.html' for writing.
When I search for this question I get lots of answers (to other questions). This is probably because the answer is very easy, but I just do not understand how to do it.
There's no need to remove the file when you can just empty it. File mode w will "open for writing, truncating the file first", and if the file doesn't exist, it will create it.
sbfldr = input('Enter subfolder name: ')
fname = os.path.join(sbfldr, 'Report.html')
with open(fname, 'w') as fwrite:
pass # Actual code here
BTW this uses a with-statement, which is the best practice for opening files. As well it ignores the bad error handling (bare except) and unnecessary exit() in your program.
Thanks to #furas for mentioning this in the comments
Try the following, using os.path.exists to check if the file exists, and os.remove to remove it if so:
import os
if os.path.exists("Report.html"):
os.remove("Report.html")
with open("Report.html", "w") as f:
pass #do your thing

How to write and read to a file in 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

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

Problems with reading and writing a text file in Python

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.

Categories

Resources