PYTHON - Read and overwrite file and add each value by one - python-2.7

I’m trying to program a simple code in python that will overwrite my existing file and also add one to every value or line in my file.
For example my “num.txt” file:
5 ---> 6
7 ---> 8
9 ---> 10
11 ---> 12
13 ---> 14
file = raw_input("Enter filename: ")
infile = open(file,'r')
for line in infile:
value = int(line)
infile.write(str(value + 1))
infile.truncate()
infile.close()
Error message:
infile.write(str(value + 1))
IOError: File not open for writing
I really appreciate your help
Thx
Geno

Your file is not open for writing, this line
infile = open(file,'r')
means that open the file for reading.
If you want to open the file for writing, you can use 'w' (write) or 'r+' (read and write) use this instead:
infile = open(file,'r+')
for more you can read (http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python) --> Mode Section.
If you use 'r+' the code should be something like
infile = open(file, 'r+')
for line in infile:
val = int(line)
infile.write(str(val + 1) + '\n')
infile.truncate()
infile.close()
But I suppose this wont serve the purpose which you want to do, this will just append the values to the end. If you want to write these new values to file, use this instead:
infile = open(file, 'r')
lines = infile.readlines() #this gives a list of all lines
infile.close()
outfile = open(file, 'w') #erases previous contents
for line in lines:
outfile.write(str(int(line) + 1) + '\n') #if you are sure file have int's only
outfile.close()

For Python 3,
filename = input("Enter filename: ")
with open(filename, 'r+') as file:
lines = file.readlines()
file.seek(0)
for line in lines:
value = int(line)
file.write(str(value + 1))
file.truncate()

Related

rstrip, split and sort a list from input text file

I am new with python. I am trying to rstrip space, split and append the list into words and than sort by alphabetical order. I don’t what I am doing wrong.
fname = input("Enter file name: ")
fh = open(fname)
lst = list(fh)
for line in lst:
line = line.rstrip()
y = line.split()
i = lst.append()
k = y.sort()
print y
I have been able to fix my code and the expected result output.
This is what I was hoping to code:
name = input('Enter file: ')
handle = open(name, 'r')
wordlist = list()
for line in handle:
words = line.split()
for word in words:
if word in wordlist: continue
wordlist.append(word)
wordlist.sort()
print(wordlist)
If you are using python 2.7, I believe you need to use raw_input() in Python 3.X is correct to use input(). Also, you are not using correctly append(), Append is a method used for lists.
fname = raw_input("Enter filename: ") # Stores the filename given by the user input
fh = open(fname,"r") # Here we are adding 'r' as the file is opened as read mode
lines = fh.readlines() # This will create a list of the lines from the file
# Sort the lines alphabetically
lines.sort()
# Rstrip each line of the lines liss
y = [l.rstrip() for l in lines]
# Print out the result
print y

How to write rows into txt file python

I have code to write files to writer and then use writer to write into csv.
This is all using 'import csv' library.
But the problem is, I have numbers like 123456789.123456789 and when it writes into csv the number got truncate into 123456789.1234. so I want to write the results to txt instead, but don't know how to write rows to txt.
if results.get('rows', []):
for row in results.get('rows'):
for i in range(len(row)):
old, new = row[i], str()
for s in old:
new += s if s in string.printable else ''
row[i]=new
writer.writerow(row)
path = '/Users/sailormoon/Desktop/'
filename = 'sailormoon.csv'
with open(path + filename, 'wt') as f:
writer = csv.writer(f, lineterminator='\n')
Pseudo code I think:
path = '/Users/sailormoon/Desktop/'
filename = 'sailormoon.txt'
with open(path + filename, 'wt') as f:
f.write(row)
what library I can use to write rows into txt for python? Thanks!
Append all your numbers to a list as strings. Then use a for loop:
numbers = ['123456789.123456789', '123453459.128967678']
with open(path + '\\numbers.txt', 'w') as out:
for n in numbers:
out.write(n + '\n')

Python : count function does not work

I am stuck on an exercise from a Coursera Python course, this is the question:
"Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:
From stephen.marquard#uct.ac.za Sat Jan 5 09:14:16 2008
You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.
Hint: make sure not to include the lines that start with 'From:'.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt"
Here is my code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
words = line.split()
if len(words) > 2 and words[0] == 'From':
print words[1]
count = count + 1
else:
continue
print "There were", count, "lines in the file with From as the first word"`
The output should be a list of emails and the sum of them, but it doesn't work and I don't know why: actually the output is "There were 0 lines in the file with From as the first word"
I used your code and downloaded the file from the link. And I am getting this output:
There were 27 lines in the file with From as the first word
Have you checked if you are downloading the file in the same location as the code file.
fname = input("Enter file name: ")
counter = 0
fh = open(fname)
for line in fh :
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
print (words[1])
counter +=1
print ("There were", counter, "lines in the file with From as the first word")
fname = input("Enter file name: ")
fh = open(fname)
count = 0
for line in fh :
if line.startswith('From '): # consider the lines which start from the word "From "
y=line.split() # we split the line into words and store it in a list
print(y[1]) # print the word present at index 1
count=count+1 # increment the count variable
print("There were", count, "lines in the file with From as the first word")
I have written all the comments if anyone faces any difficulty, in case you need help feel free to contact me. This is the easiest code available on internet. Hope you benefit from my answer
fname = input('Enter the file name:')
fh = open(fname)
count = 0
for line in fh:
if line.startswith('From'):
linesplit =line.split()
print(linesplit[1])
count = count +1
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for i in fh:
i=i.rstrip()
if not i.startswith('From '): continue
word=i.split()
count=count+1
print(word[1])
print("There were", count, "lines in the file with From as the first word")
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
for line in fh:
if line.startswith('From'):
line=line.rstrip()
lt=line.split()
if len(lt)==2:
print(lt[1])
count=count+1
print("There were", count, "lines in the file with From as the first word")
My code looks like this and works as a charm:
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
count = 0 #initialize the counter to 0 for the start
for line in fh: #iterate the document line by line
words = line.split() #split the lines in words
if not len(words) < 2 and words[0] == "From": #check for lines starting with "From" and if the line is longer than 2 positions
print(words[1]) #print the words on position 1 from the list
count += 1 # count
else:
continue
print("There were", count, "lines in the file with From as the first word")
It is a nice exercise from the course of Dr. Chuck
There is also another way. You can store the found words in a separate empty list and then print out the lenght of the list. It will deliver the same result.
My tested code as follows:
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
newl = list()
for line in fh:
words = line.split()
if not len(words) < 2 and words[0] == 'From':
newl.append(words[1])
else:
continue
print(*newl, sep = "\n")
print("There were", len(newl), "lines in the file with From as the first word")
I did pass the exercise with it as well. Enjoy and keep the good work. Python is so much fun to me even though i always hated programming.

python script for limit text file words

I have an input file like:
input.txt:
to
the
cow
eliphant
pigen
then
enthosiastic
I want to remove those words which has character length is <= 4 , and if some word has more than 8 character then write those word in new file till 8 character length
output should be like:
output.txt:
eliphant
pigen
enthosia
This is my code:
f2 = open('output.txt', 'w+')
x2 = open('input.txt', 'r').readlines()
for y in x2:
if (len(y) <= 4):
y = y.replace(y, '')
f2.write(y)
elif (len(y) > 8):
y = y[0:8]
f2.write(y)
else:
f2.write(y)
f2.close()
print "Done!"
when i compile it then it gives the output like:
eliphantpigen
then
enthosia
it also writes 4 character length word... i don't understand what is the problem and how to write the code to limit character length of text file words....?
Use with when working with files, this guarantees that file would be closed.
You have then in your results because your are reading lines and not worlds.
Each line have symbol of ending '\n'. So when you are reading world then you have string
'then\n' and len of this string is 5.
with open('output.txt', 'w+') as ofp, open('input.txt', 'r') as ifp:
for line in ifp:
line = line.strip()
if len(line) > 8:
line = line[:8]
elif len(line) <= 4:
continue
ofp.write(line + '\n')

Python script to delete specific word in text file line

i have a text file with some site links.... i want to remove the string which is before the site name.
here is the input file >>
input.txt:
http://www.site1.com/
http://site2.com/
https://www.site3333.co.uk/
site44.com/
http://www.site5.com/
site66.com/
output file should be like:
site1.com/
site2.com/
site3333.co.uk/
site44.com/
site5.com/
site66.com/
here is my code:
bad_words = ['https://', 'http://', 'www.']
with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
for line in oldfile:
if not any(bad_word in line for bad_word in bad_words):
newfile.write(line)
print './ done'
when i run this code then it totally remove the lines which containing bad_words
site44.com/
site66.com/
what should i do with code to get my specific result?
Thanks all i have solved this... code should be:
fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = ['https://', 'http://', 'www.']
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
print './ done'