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.
Related
I used Python 3.6 version and now I want to save name & age at the file and then read the text as name + tab + age but I can't approach file read side.
My code:
while True:
print("-------------")
name=input("Name: ")
age=input ("Age: ")
contInput=input("Continue Input? (y/n) ")
fp.open("test.txt", "a")
fp.write(name+","+age+"\n")
if contInput=="n":
fp.close()
break
else:
continue
with open("test.txt", "r") as fp:
rd = fp.read().split('\n')
????
fp.close()
so I just confuse about file read. I want to print my saved data like below.
name [tab] age
but after used split method, rd type is list.
Can I divide name & age as each items?
fp.open("test.txt", "a")
At this point in your program, fp doesn't exist yet. Perhaps you meant fp = open(...) instead?
You're only closing the file if the user chose not to continue, but you're opening it every time through the loop. You should open and close it only once, or open and close it every time through the loop.
fp.write(name+","+"age"+"\n")
This writes the literal word age instead of the age variable. You probably wanted this instead: fp.write(name + "," + age + "\n")
Try this for your input loop:
with open("test.txt", "r") as fp:
for line in fp:
data = line.split(",")
name = data[0]
age = data[1]
This question already has answers here:
Correct way to write line to file?
(17 answers)
Closed 6 years ago.
I'm trying to write some text to a file, and here's what i tried :
text = "Lorem Ipsum is simply dummy text of the printing and typesetting " \
"industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
" when an unknown printer took a galley of type and scrambled it to make a type specimen book."
target = open("file", 'wb')
target.writelines(text)
And I get an empty file.
How can I do this?
This is how to print to a txt file:
file = open("Exported.txt", "w")
file.write("Text to write to file")
file.close() #This close() is important
Another way to do so would to be:
with open('Exported.txt', 'w') as file:
file.write("Text to write to file")
This is a program I made to write a txt file:
import os.path
def start():
print("What do you want to do?")
print(" Type a to write a file")
print(" Type b to read a file")
choice = input(" -")
if choice == "a":
create()
elif choice == "b":
read()
else:
print("Incorrect spelling of a or b\n\n")
start()
def create():
print()
filename = input("What do you want the file to be called?\n")
if os.path.isfile(filename):
print("This file already exists")
print("Are you sure you would like to overwrite?")
overwrite = input("y or n")
if overwrite == "y":
print("File has been overwritten")
write(filename)
else:
print("I will restart the program for you")
elif not os.path.isfile(filename):
print("The file has not yet been created")
write(filename)
else:
print("Error")
def write(filename):
print()
print("What would you like the word to end writing to be?")
keyword = input()
print("What would you like in your file?")
text = ""
filename = open(filename, 'w')
while text != keyword:
filename.write(text)
filename.write("\n")
text = input()
def read():
print()
print("You are now in the reading area")
filename = input("Please enter your file name: -")
if os.path.isfile(filename):
filename = open(filename, 'r')
print(filename.read())
elif not os.path.isfile(filename):
print("The file does not exist\n\n")
start()
else:
print("Error")
start()
writelines expects an iterable (e.g. a list) of lines, so don't use that. And you need to close the file to save the changes, which is best done with a with statement:
with open("file", 'wb') as target:
target.write(text)
The code you've provided produces a file named file with the desired lines. Perhaps you meant to save it as "file.txt". Also, the 'b' in the 'wb' flag tells the code to write the file in binary mode (more information here). Try just using 'w' if you want the file to be readable.
Finally it is best practice to use the with statement when accessing files
text ="Lorem Ipsum is simply dummy text of the printing and typesetting " \
"industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," \
" when an unknown printer took a galley of type and scrambled it to make a type specimen book."
with open("file.txt", 'w') as f:
f.write(text)
By this way you should close the file directly:
target = open("filename.txt", 'w')
target.writelines(text)
target.close()
By this way the file closed after the indented block after the with has finished execution:
with open("filename.txt", "w") as fh:
fh.write(text)
See here for more info.
I am using Python 2.7 and am trying to get my program to check if a file exists and if it does, the program should then ask the user if they want to overwrite it. If the file is not there, a new one should be created. These two steps are repeated where the file is found to be existing. Here is the code:
import os.path
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
print ("File exists")
decide = input("Do you want to overwrite the file?, Yes or No")
control = True
while control:
if decide != "Yes":
file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
if os.path.isfile(file_name):
print ("File exists")
else:
newFile = open(file_name, "w")
newFile.write(str(model))
newFile.close()
control=False
else:
print("Creating a new file..................")
file_open.write(str(model))
file_open.close()
In lines 2, 6 and 10 it should be raw_input() as you are reading string, and check indentation of code.
I need to omit all the information before '* START' and after '* END' in the txt file we open in Python(so the .txt is only the body)
We were given a string parameter and have written. it continues to write out the original .txt instead of just the body
def copy_file_2(s:str):
"that if its parameter is 'Gutenberg trim' it will copy only the body of a Project Gutenberg file, omitting the "housekeeping" material at the front and end. "
infile_name = input("Please enter the name of the file to copy: ")
infile = open(infile_name, 'r', errors = 'ignore')
outfile_name = input("Please enter the name of the new copy: ")
outfile = open(outfile_name, 'w')
if s == 'Gutenberg trim':
infile_data = infile.readlines()
for i in range(len(infile_data)):
t = '{:5d}: {}'.format(i+1,infile_data[i])
if "*** START" in t:
outfile.write(t)
else:
for line in infile:
outfile.write(line)
infile.close()
outfile.close()
print re.search("START(.*)END",open("some_file").read(),re.DOTALL).groups()[0]
Im pretty sure should work fine for you ...
def function(score,name):
sumOfStudent = (name + ' scored ' + str(score))
f = open('test.txt', 'wb')
f.write(sumOfStudent)
f.close()
user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))
function(user_score,user_name)
f = open('test.txt')
print(f.read())
f.close()
I was writing a simple program in python which allowed the user to enter information and then for that text to be stored in a .txt file. This worked however it would always write to the same line, I was wondering how I would make the f.write(sumOfStudent) on a new line every time (sumOfStudent is the variable to hold user input) Thanks!
Hey what you are doing is not writing to the end of the file you are overwriting everytime 'w' what you need to be doing is appending it to the file by using 'a'
f = open('test.txt', 'a')
Also to write to a new line you must tell the program thats what you're doing by declaring a new line "\n"
f.write(sumOfStudent + "\n")