Why doesn't this write data into the created file? Python - python

Why does this create the file but not write the code into it?
import os
#List for text
mainlist = []
#Definitions
def main():
print("Please Input Data(Type 'Done' When Complete):")
x = input()
if x.lower() == 'done':
sort(mainlist)
else:
mainlist.append(x)
main()
def sort(mainlist):
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?:")
filename = input()
with open(filename + ".txt", "w") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
The file is made, and the data is stored... But finalstring's content isn't written into it. The file remains blank.

You're calling sort(mainlist) multiple times and the file is being overwritten each time. Change the open mode to a like:
with open(filename + ".txt", "a") as f:
f.write(str(finalstring))
See http://docs.python.org/3.2/tutorial/inputoutput.html#reading-and-writing-files

Related

Finding desired search result from list in Txt file with python

def add():
while True:
try:
a = int(input("How many words do you want to add:"))
if a >= 0:
break
else:
raise ValueError
except ValueError:
print("Not valid ")
return a
for i in range(add()):
key_i = input(f"Turkish meaning: {i + 1}: ")
value_i = input("translated version: ")
with open('words.txt', 'a+') as f:
f.write("'"+key_i+':')+ f.write(value_i+"'"+",")
My goal is to create my own dictionary,but I am adding a list into the txt file, so it is added into the txt file like this
words = {'araba:kol',
but when I search the txt file it gives me the whole list
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('words.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
What can I do to make it output like this
car:araba
Use JSON module to avoid having to write the dictionary line by line yourself.
import json
with open('words.json', 'a+') as f:
json.dump({key_i: value_i}, f)
with open('data.json', 'r') as f:
d2 = json.load(f)
d2 is now the data that you wrote to the file.
Note, that you should change the a+ to 'w' as you only have one dictionary per file.

How to add numbers to a file

I'm a beginner at Python and I just learned about opening files, reading files, writing files, and appending files.
I would I like to implement this to a little project that I'm making that asks for the user's name and appends it to a txt file named "HallOfFame.txt"
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.read()
print(file_contents)
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + '\n')
name_file.close()
Everytime someone adds their name, I'd like it to become something like this:
Vix
Mike
Valerie
Something similar like that (above) where they have to run the program again to see the Hall of Fame.
Thank you!
I can understand your question. you can try using the JSON module and do something like this.
import json
list = [1, "Vix"]
with open ('HallOfFame.txt', 'w') as filehandle:
json.dump(list, filehandle)
here you can update the list every time you get input. and write it to the text file. but the appearance will look like this.
[1, "Vix"]
[2, "Mike"]
[3, "Valerie"]
count = 0
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.readlines()
if len(file_contents) != 0:
print("\nHall of Fame")
for line in file_contents:
count += 1
print("{}. {}".format(count, line.strip()))
print()
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + "\n")
name_file.close()

NameError for filename?

I'm trying to write a program that assigns prices to a list, but I'm having trouble. I keep getting a NameError, that costlist is not defined. The program should ask for an input, append it to the list, and go through the whole list, then write it to the .txt file.
import os
def main():
if os.path.exists("costlist.txt"):
os.remove("costlist.txt")
print ("Assignment 6")
print ()
filename = input("Enter a file name, please. Or enter end to end.")
while filename != "end":
try:
file = open(filename, "r")
listie = file.readlines()
for item in listie:
print(item)
break
except FileNotFoundError:
filename = input("Sorry, that file wasn't found. Try again?")
if filename == "end":
exit
file.close()
listie.sort()
file = open(filename, "w")
for item in listie:
file.write(item.strip("\n"))
file.close()
for item in listie:
cost = input(print( item + "should cost how much?"))
try:
float.cost
except ValueError:
print ("You entered an invalid float that can't convert string to float:" + cost)
print ("Skipping to the next item after" + item)
print (item + "has a cost of" + cost + "dollars")
file = open(costlist.txt, "a")
file.append(cost)
print ("Cost List")
file = open (costlist.txt, "r")
for item in file:
print (item)
print ("Program End")
You forgot to enclose the file name by quotes.
Change file = open(costlist.txt, "a") to file = open("costlist.txt", "a")
And
file = open (costlist.txt, "r") to file = open ("costlist.txt", "r")

Error being written to file when trying to write output

In this spellchecking program i created i seem to be getting a error when trying to write to the output file.The file is created but instead of the output being written an error " <_io.TextIOWrapper name='f.txt' mode='w' encoding='cp1252'>name " is.
I've tried looking for solutions.
print('Spell checking program for Exam 3 lab')
inputFile = input('Enter the name of the file to input from: ')
outputFile = input('Enter the name of the file to output to: ')
f = open("linuxwords.txt", "r")
sent = open(inputFile+ '.txt', "r")
butt = open(outputFile+'.txt', 'w')
word = sent.readline()
print ("mispelled words are:")
while word:
word = word.lower()
success = False
x = word.split()
y=len(x)
for i in x:
success = False
f = open("linuxwords.txt", "r")
line = f.readline()
while line:
if i == line.strip():
success = True
break
line = f.readline()
f.close()
if success == False:
print (i)
word = sent.readline()
with open(outputFile+'.txt', 'w') as f:
f.write(str(butt))
f.write(i)
try:
'''''''
I'm sure my mistake is here, idk
'''''''
f = open(outputFile, "w")
f.write(i)
except:
print('The file',outputFile, 'did not open.')
sent.close()
''''''
Result below
''''''''
Spell checking program for Exam 3 lab
Enter the name of the file to input from: spw
Enter the name of the file to output to: f
misspelled words are:
deks
chris
delatorre
huis
lst
f = open(outputFile)
f.write(i)
You're opening the file for reading, and then trying to write to it.

Change text in file with Python

def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()

Categories

Resources