My simple assignment is to write a function that asks for a filename, and then repeatedly reads lines from the user and saves these lines to the named file.
It stops saving the lines when the user input is a single dot on a line by itself. The line containing the single dot is NOT saved.
Example output would look like:
Save to what file: mytest.txt
> This is
> my attempt at
> the problem.
>
> The last line was empty
> .
Saving file mytest.txt
5 lines saved
Here's my attempt:
def savefile():
filename = input("Save to what file: ")
infile = open(filename, "w")
line = ""
lineCount = 0
while line != ".":
line = input("> ")
infile.write(line + "\n")
lineCount += 1
print("Saving file", filename)
print(lineCount, "lines saved")
infile.close()
which works fine, except my while loop also saves the last line (the "." by itself on a line). I've also tried an if-else loop:
if line != ".":
line = input("> ")
infile.write(line + "\n")
lineCount += 1
else:
infile.close()
but this just saves the first line entered.
How can I exclude the last line entered?
Doesn't even need an explanation:
with open("my_file.txt","w") as file:
while True:
line = input("> ")
if line.strip() == ".":
break
else:
file.write(line + "\n")
You could try this by simply interchanging some of the lines in your code as follows:
def savefile():
filename = input("Save to what file: ")
infile = open(filename, "w")
line = input("> ")
lineCount = 0
while line != ".":
infile.write(line + "\n")
lineCount += 1
line = input("> ")
print("Saving file", filename)
print(lineCount, "lines saved")
infile.close()
It is just a little out of order, classic problem, move the input to above the while loop, I hope see why...
def savefile():
filename = input("Save to what file: ")
infile = open(filename, "w")
line = ""
lineCount = 0
# first lets get the line of input
line = input("> ")
# if the line is "." then don't do the following code.
while line != ".":
# if the line was not "." then we do this...
infile.write(line + "\n")
lineCount += 1
# get the input again, and loop, remember if we get "."
# we will break from this loop.
line = input("> ")
print("Saving file", filename)
print(lineCount, "lines saved")
infile.close()
Related
#This program takes in a text file and whatever the ser types in ; it searches for the specific word or phrase and then print out in which line this word or phrase is located .
If i feed it a text file with 20 lines , it produces normal results
As soon as i give it a 3000 worded document it produces error
Can anyone explain this
while True:
search = str(input("==>"))
line_number = 1
fslope = open("searching_in_a_textfile")
for line in fslope:
if search.lower() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
if search.upper() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
if search.title() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
else:
line_number = line_number + 1
continue
print("END OF PRIOCESS")
First lets make it simple: (this code is almost the same as yours)
lines = []
with open('searching_in_a_textfile') as f:
lines = f.readlines()
while True:
search = input('==>')
if not search:
break
for line_number, line in enumerate(lines, 1):
if search.lower() in line.lower():
print('tHE LINE NUMBER IS ', line_number, '\nTHE LINE SAYS :', line)
print("END OF PRIOCESS")
Now when the input is '' (empty string / no input) the process will stop.
if you can add your error it could be very helpful.
For some reason, I cannot seem to find where I have gone wrong with this program. It simply takes a file and reverses the text in the file, but for some reason all of separate sentences print on a new and I need them to print on the same line.
Here is my code for reference:
def read_file(filename):
try:
sentences = []
with open(filename, 'r') as infile:
sentence = ''
for line in infile.readlines():
if(line.strip())=='':continue
for word in line.split():
if word[-1] in ['.', '?', '!']:
sentence += word
sentences.append(sentence)
sentence = ''
else:
sentence += word + ' '
return sentences
except:
return None
def reverse_line(sentence):
stack = []
punctuation=sentence[-1]
sentence=sentence[:-1].lower()
words=sentence.split()
words[-1] = words[-1].title()
for word in words:
stack.append(word)
reversed_sentence = ''
while len(stack) != 0:
reversed_sentence += stack.pop() + ' '
return reversed_sentence.strip()+punctuation
def main():
filepath = input('File: ')
sentences = read_file(filepath)
if sentences is None:
print('Unable to read data from file: {}'.format(filepath))
return
for sentence in sentences:
reverse_sentence = reverse_line(sentence)
print(reverse_sentence)
main()
You can use the end keyword argument:
print(reverse_sentence, end=' ')
The default value for the end is \n, printing a new-line character at the end.
https://docs.python.org/3.3/library/functions.html#print
When the following bit of code runs, most specifically the last 'else'condition, I get this error: OSError: [Errno 22] Invalid argument: 'My Name\n-Groups.txt'
What should I do so that '\n' isn't included in the file name as I would like it to just be 'My Name-Groups.txt'.
def add_child_to_group():
file = open("Children.txt", 'r') # open the Children.txt file
lineList = file.readlines()
lineList.sort()
file.close()
choice1 = choicebox('Choose a child to enter into a group.', 'Add child to a group. ', choices=lineList)
if choice1 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
file = open("Groups.txt", 'r')
lineList = [line.strip() for line in file]
choice2 = choicebox("Which group would you like to add the child to?", "Choose a group.",
choices=lineList)
file.close()
if choice2 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
if choice1 in open('%s.txt' % choice2).read():
child_already_in_group(choice1, choice2)
return
else:
file1 = open('%s.txt' % choice2, 'a')
file1.write(str(choice1))
print(str(choice1) + "was added to the " + str(choice2) + " group")
file1.close()
file2 = open('%s-Groups.txt' % choice1, 'a')
file2.write(str(choice2))
Something like this can do:
>>> st = 'My Name\n-Groups.txt'
>>> st.replace('\n','')
'My Name-Groups.txt'
>>>
So, in your code, you can make the following change:
file2 = open(('%s-Groups.txt' % choice1).replace('\n',''), 'a')
So I keep trying to make this work but I do not know where it is going wrong. The text file contains:
III
###
This is what I have so far. I do not see what is wrong.
CHARACTERS = ["I","#"]
def checkFile():
inFile = open("random.txt","r")
text = inFile.read()
inFile.close()
x = True
for line in text:
line.strip()
for i in range(len(line)):
if line[i] in CHARACTERS:
x = True
else:
x = False
return False
return True
def main():
check = checkFile()
if check == False:
sys.exit()
elif check == True:
print("bye")
sys.exit()
main()
It should print "bye" because all the characters in the file are in the list; however it just exits without the print statement.
When a txt file contains two lines of text, one on top of each other, it also includes a hidden '\n'. To change that add '\n' to CHARACTERS, or copy the following code:
CHARACTERS = ["I","#", "\n"]
def checkFile():
inFile = open("random.txt","r")
text = inFile.read()
inFile.close()
x = True
for line in text:
line.strip()
for i in range(len(line)):
if line[i] in CHARACTERS:
x = True
else:
x = False
return False
return True
def main():
check = checkFile()
if check == False:
sys.exit()
elif check == True:
print("bye")
sys.exit()
main()
EDIT: I created a txt file called test.txt and I pasted your text into it. I then ran the following code:
>>> file = open('test.txt', 'r').read()
>>> file
'III\n\n###\n'
>>>
Because there are two lines in between, it has teo '\n's. You can get rid of this by either adding '\n' to CHARACTERS, or by calling text = inFile.read().split() with the split()
When you call line.strip(), you are not assigning line.strip() to any value. Thus, the '\n' remains 'unstripped', so to speak. Instead, call line = line.strip().
I don't know where does it goes wrong. I can get the correct result if I just call out my valid_ISBN(isbn) function, but when I write the file, the result become all invalid. (maybe something wrong with function call, but I don't know how to fix it)
def main():
# Call and open the File
inFile = open("isbn.txt", "r")
for line in inFile:
line_strip = line.replace("-", "").replace(" ", "").rstrip("\n")
isbn = line_strip # the function call
# Output file
str = []
str.append(line)
outFile = open("isbnOut.txt", "a")
for i in str:
if valid_ISBN(isbn) == "valid":
outFile.write(i.strip() + " valid\n")
else:
outFile.write(i.strip() + " invalid\n")
inFile.close()
outFile.close()
def valid_ISBN(isbn):
if len(isbn) != 10 or (isbn[0:9].isdigit()) == False:
print("invalid")
else:
return partial_sums(isbn)
def partial_sums(s1):
lst1 =[]
sum1 = 0
for i in range(len(s1)):
if (i == (len(s1) -1)) and ((s1[i] == "x") or (s1[i] == "X")):
sum1 = sum1 + 10
else:
sum1 = sum1 + int(s1[i])
lst1.append(sum1)
#print(lst1)
sum_of_s1(lst1)
def sum_of_s1(s2):
lst2 = []
sum2 = 0
for i in s2:
sum2 += i
lst2.append(sum2)
#print(lst2)
checkISBN(lst2[-1])
def checkISBN(value):
if value % 11 == 0:
print("valid")
else:
print("invalid")
main()
2 Test case for isbn text file (no new line):
019-923-3241
818-851-703X
In your main function:
Every time you read a line in from your input file you initialize str and fill it with just one value. You open your output file, do your validity checks for your one value in str, and finally write the one value to the the output file.
The next time you read the file you do the same stuff... so str isn't needed at all
Also using str as a variable name is bad form. In your console write in help(str) and you will see why.
Now to deal with your actual complaint:
Your problem is the fact that there is no new line.
when you say for line in some_open_file_handler:... what python does is populate line with everything up to the next newline character or the end of the file.
If your input file has no new lines seperating isbns then the first value of line would be 019-923-3241 818-851-703X. Thus the line line_strip = line.replace("-", "").replace(" ", "").rstrip("\n") set linestrip to 0199233241818851703X
This should fix it:
'line.split() will yield ['019-923-3241','818-851-703X']
outFile = open("isbnOut.txt", "a")
for line in open("isbn.txt", "r"):
isbns = line.split() #this splits stuff up by whitespace.
for isbn in isbns:
isbn = isbn.replace("-", "").replace(" ", "").rstrip("\n")
if valid_ISBN(isbn) == "valid":
outFile.write(i.strip() + " valid\n")
else:
outFile.write(i.strip() + " invalid\n")