Write user input to file python - python

I can't figure out how to write the user input to an existing file. The file already contains a series of letters and is called corpus.txt . I want to take the user input and add it to the file , save and close the loop.
This is the code I have :
if user_input == "q":
def write_corpus_to_file(mycorpus,myfile):
fd = open(myfile,"w")
input = raw_input("user input")
fd.write(input)
print "Writing corpus to file: ", myfile
print "Goodbye"
break
Any suggestions?
The user info code is :
def segment_sequence(corpus, letter1, letter2, letter3):
one_to_two = corpus.count(letter1+letter2)/corpus.count(letter1)
two_to_three = corpus.count(letter2+letter3)/corpus.count(letter2)
print "Here is the proposed word boundary given the training corpus:"
if one_to_two < two_to_three:
print "The proposed end of one word: %r " % target[0]
print "The proposed beginning of the new word: %r" % (target[1] + target[2])
else:
print "The proposed end of one word: %r " % (target[0] + target[1])
print "The proposed beginning of the new word: %r" % target[2]
I also tried this :
f = open(myfile, 'w')
mycorpus = ''.join(corpus)
f.write(mycorpus)
f.close()
Because I want the user input to be added to the file and not deleting what is already there, but nothing works.
Please help!

Open the file in append mode by using "a" as the mode.
For example:
f = open("path", "a")
Then write to the file and the text should be appended to the end of the file.

That code example works for me:
#!/usr/bin/env python
def write_corpus_to_file(mycorpus, myfile):
with open(myfile, "a") as dstFile:
dstFile.write(mycorpus)
write_corpus_to_file("test", "./test.tmp")
The "with open as" is a convenient way in python to open a file, do something with it while within the block defined by the "with" and let Python handles the rest once you exit it (like, for example, closing the file).
If you want to write the input from the user, you can replace mycorpus with your input (I am not too sure what you want to do from your code snippets).
Note that no carriage return is added by the write method. You probably want to append a "\n" at the end :-)

Related

I/O operation on closed file; trying to print on-screen after writing to a file

I'm trying to write the contents of the screen to a text file if the user selects that option. However, Python seems to want to print "Report Complete." to the report.txt file, which I told it to close. I want the "report complete" to display on the screen after it writes to the text file, and move on to the hashing function.
import wmi
import sys
import hashlib
c = wmi.WMI()
USB = "Select * From Win32_USBControllerDevice"
print ("USB Controller Devices:")
for item in c.query(USB):
print (item.Dependent.Caption)
print (" ")
print ("======================================")
report = input ("Would you like the results exported to a file? ")
if (report) == "yes":
file = open('report.txt', 'w')
sys.stdout = file
for item in c.query(USB):
print (item.Dependent.Caption)
file.close()
print ("Report complete.")
else:
print ("Job Complete.")
hashInput = input ("Would you like to hash the report? ")
if (hashInput) == "yes":
hash = hashlib.md5(open('report.txt', 'rb').read()).hexdigest()
print ("The MD5 hash value is:", (hash))
else:
print ("Job Complete.")
You set sys.stdout to a file, and then closed the file. That makes everything you try and print, which would normally go to stdout, try and go to a closed file. If I may suggest, don't reassign sys.stdout. It is not necessary.
if report == "yes":
with open('report.txt', 'w') as fout:
for item in c.query(USB):
print(item.Dependent.Caption, file=fout)
print("Report complete.")

Python code isnt printing contents of txt?

elif menuOption == "2":
with open("Hotel.txt", "a+") as file:
print (file.read())
Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.
if menuOption == "1":
print("Please Type Your Guests Name.")
data1 = (input() + "\n")
for i in range (2,1000):
file = open("hotel.txt", "a")
file.write(data1)
print("Please Write your Guests Room")
data2 = (input("\n") + "\n")
file.write(data2)
data3 = random.randint(1, 999999)
file.write(str (data3))
print("Guest Added - Enjoy Your Stay.")
print("Guest Name is:", data1)
print("Guest Room Number Is:", data2)
print("Your Key Code Is:", data3)
I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work.
Why and how can I fix?
You have to use r instead of a+ to read from file:
with open("Hotel.txt", "r") as file:
You are using a+ mode which is meant for appending to the file, you need to use r for reading.
Secondly I notice this
for i in range (2,1000):
file = open("hotel.txt", "a")
You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.
with open("hotel.txt", "a") as fh:
do your processing here...
This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.
Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.
name = input("Enter your name: ")

Python 3.6 new line with user input

Made a program that allows the user to enter some text and have a text file be created with that text inside it. However, when the user puts \n it doesn't start a new line. Finding it very difficult to use my program to create text files as it writes all the text on one line lol
Thanks
EDIT - Sorry. Here is my code (Just the part we are concerned with).
class ReadWriteEdit:
def Read(File):
ReadFile = open(File,"r").read()
print(ReadFile)
def Write(File, Text):
WriteFile = open(File,"w")
WriteFile.write(Text)
def Edit(File, Text):
EditFile = open(File,"a")
EditFile.write(Text)
def Write():
print("WRITE")
print("Enter a file location / name")
FileInput = input("-:")
print("Enter some text")
TextInput = input("-:")
ReadWriteEdit.Write(FileInput, TextInput)
As you have found, special escaped characters are not interpolated in strings read from input, because normally we want to preserve characters, not give them special meanings.
You need to do some adjustment after the input, for example:
>>> s=input()
hello\nworld
>>> s
'hello\\nworld'
>>> s = s.replace('\\n', '\n')
>>> s
'hello\nworld'
>>> print(s)
hello
world
You can just add your input to the variable. You didn't provide any code so I'll just have to improvise:
data = open('output.txt', 'w')
a = input('>>')
data.write(a + '\n')
data.close()
But the better solution would be, like the comment below me mentioned, to use sys.stdin.readline()
import sys
data.write(sys.stdin.readline())
The easiest (dirtiest?) way IMHO is to print the message and then use input() without a prompt (or with the last part of it)
print("Are we REALLY sure?\n")
answer = input("[Y/n]")

Format path within Text File for consumption in Python

I am writing a Python script for use by multiple non-Python users.
I have a text file containing the parameters my script needs to run.
One of the inputs is a path. I cannot get my script to run and was thinking it was because I had referenced my path incorrectly.
I have tried:
C:\temp\test
"C:\temp\test"
r"C:\temp\test"
C:/temp/test
"C:/temp/test"
C:\\temp\\test
"C:\\temp\\test"
I have added each one of these into a text file, which is called and read in my Python script.
I have other parameters and they are called correctly, my script seems to run when I hard code the path in. I say seems because I think there are a few bugs I need to check, but it runs with no errors.
When I use the text file I get this error - which varies depending on if I used one of the above examples:
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect: 'c:\temp\match1\jpg\n/.'
My code is as follows:
print ("Linking new attachments to feature")
fp = open(r"C:\temp\Match1\Match_Table.txt","r") #reads my text file with inputs
lines=fp.readlines()
InFeat = lines[1]
print (InFeat)
AttFolder = lines[3] #reads the folder from the text file
print (AttFolder)
OutTable = lines[5]
if arcpy.Exists(OutTable):
print("Table Exists")
arcpy.Delete_management(OutTable)
OutTable = lines[5]
print (OutTable)
LinkF = lines[7]
print (LinkF)
fp.close()
#adding from https://community.esri.com/thread/90280
if arcpy.Exists("in_memory\\matchtable"):
arcpy.Delete_management("in_memory\\matchtable")
print ("CK Done")
input = InFeat
inputField = "OBJECTID"
matchTable = arcpy.CreateTable_management("in_memory", "matchtable")
matchField = "MatchID"
pathField = "Filename"
print ("Table Created")
arcpy.AddField_management(matchTable, matchField, "TEXT")
arcpy.AddField_management(matchTable, pathField, "TEXT")
picFolder = r"C:\temp\match1\JPG" #hard coded in
print (picFolder)
print ("Fields added")
fields = ["MatchID", "Filename"]
cursor = arcpy.da.InsertCursor(matchTable, fields)
##go thru the picFolder of .png images to attach
for file in os.listdir(picFolder):
if str(file).find(".jpg") > -1:
pos = int(str(file).find("."))
newfile = str(file)[0:pos]
cursor.insertRow((newfile, file))
del cursor
arcpy.AddAttachments_management(input, inputField, matchTable, matchField, pathField, picFolder)
From your error "'c:\temp\match1\jpg\n/.'", i can see "\n" character, \n is symbole of new line ( when you press enter button ) you should remove that character from end of your path! did you try to do that? you can use .lstrip("\n") , replcae() or regx methods for remove that character.
Try to open and read line by line of your input file like this:
read_lines = [line.rstrip('\n') for line in open(r"C:\temp\Match1\Match_Table.txt")]
print(read_lines)
print(read_lines[1])

Weird characters and deficiency of the attribute. Python

I've created a function and got stuck on it.
Meaning of the function:
User types in a file, number and own name.
Program writes the name at the end of the file 'number' times.
And just prints out contents of the file.
What's the problem?
There are strange characters and a big space under it when program reads the file.
Like this: ਍圀漀爀氀搀眀椀搀攀㬀 ㈀  㐀 ⴀ 瀀爀攀猀攀渀琀ഀഀ (and then there is a huge space for 10-15 lines in Powershell)
Error: 'str' object has no attribute 'close'.
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
open_file = open(file_name, 'a+')
listok = []
while len(listok) < enter_1:
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
read_file = open_file.read()
print read_file
file_name.close()
filemania()
I think the problem is somewhere here:
open_file = open(file_name, 'a+')
Does somebody know how to solve these problems?
Firstly you set file_name = raw_input("Type in any text file> ") so you are trying to close a string with file_name.close():
When you write to open_file you move the pointer to the end of the file because you are appending so read_file = open_file.read() is not going to do what you think.
You will need to seek to the start of the file again to print the content, open_file.seek(0).
def filemania():
print "Great! This way is called \"Filemania\""
file_name = raw_input("Type in any text file> ")
enter_1 = int(raw_input("Enter an integer> "))
enter_2 = raw_input("Enter your name> ")
print "Now your name will apear in the file %d times at the end" % enter_1
# with automatically closes your files
with open(file_name, 'a+') as open_file:
listok = []
# use range
for _ in range(enter_1):
open_file.write(enter_2 + " ")
listok.append(enter_2)
print "Contains of the file:"
# move pointer to start of the file again
open_file.seek(0)
read_file = open_file.read()
print read_file
filemania()
For your second error, you are trying to close file_name, which is the raw input string. You mean to close open_file
Try that and report back.

Categories

Resources