How to write rows into txt file python - python-2.7

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')

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 insert two file.txt into one file

I have this function that takes two input .txt file, delete the punctuation mark, and adds the sentence pos or neg.
I would like the content of these fle converted to lowercase
and then these two files merged into a single file name union.txt
But my code does not work
def extractor (feature_select):
posFeatures = []
negFeatures = []
with open('positive.txt', 'r') as posSentences:
for i in posSentences:
posWords = re.findall(r"[\w']+|[(,.;:*##/?!$&)]", i.rstrip())
posWords = [feature_select(posWords), 'pos']
posFeatures.append(posWords)
with open('negative.txt', 'r') as negSentences:
for i in negSentences:
negWords = re.findall(r"[\w']+|[(,.;:*##/?!$&)]", i.rstrip())
negWords = [feature_select(negWords), 'neg']
negFeatures.append(negWords)
return posFeature, negFeature
filenames = [posFeature, negFeature]
with open('union.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
Actually you are trying to open the files with names from the contents of the two files. fname holds the contents read from the input files.
filenames = [posFeature, negFeature]
with open('union.txt', 'w') as outfile :
for i in filenames : #refers to posFeature or negFeature which is a list
for j in i: #this loop reads each sentence from the list i
outfile.write(j) #it writes the sentence into outfile
No need to read back the contents already read and appended in posFeature and negFeature. Above code will directly write the contents in the list filenames and now your two files are merged.

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

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()

Python: program not writing to file after breaking the loop

I am fairly new to Python, and I am messing around with code and I am wondering why my code, when the for loop is broken, does not write to the file.
But, when I do not break the for loop, it writes to the file over and over again with no end, deleting the previous content (I only want it to loop through once and get the data on the first iteration of it):
def runExtract(self):
with open(self.fileIn) as f:
content = f.readlines()
#query = f.readlines()
for query in content:
result=google_search.SearchEngine.search(query, 3)
"""junk"""
file1=open(self.fileOutGoog,'r+b')
"""junk"""
for k in result:
#file.write(str(k.name)+"\t")
file1.write(str(k.link)+"\t")
#file.write(str(k.description)+"\t")
file1.write("\n")
#file=open(self.fileOutGoog,'rb')
file1.flush() """writes to file, deleting the '/url?q=' from html"""
file1.close()
file1 = open(self.fileOutGoog,'r')
filedata = file1.read()
file1.close()
newdata = filedata.replace('/url?q=','')
file1 = open(self.fileOutGoog,'w')
file1.write(newdata)
file1.flush()
file1.close()
result=bing_search.SearchEngine.search(query, 3)
"""junk"""
file2=open(self.fileOutBing,'w')
for k in result:
#file.write(str(k.name)+"\t")
file2.write(str(k.link)+"\t")
# file.write(str(k.description)+"\t")
file2.write("\n")
file2.flush()
file2.close()
break
print("done - check dir for results")
f.flush()
f.close()
I have been trying to fix this for two days straight, but I have not succeeded.

Python CSV export writing characters to new lines

I have been using multiple code snippets to create a solution that will allow me to write a list of players in a football team to a csv file.
import csv
data = []
string = input("Team Name: ")
fName = string.replace(' ', '') + ".csv"
print("When you have entered all the players, press enter.")
# while loop that will continue allowing entering of players
done = False
while not done:
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ")
print (string)
file = open(fName, 'w')
output = csv.writer(file)
for row in string:
tempRow = row
output.writerow(tempRow)
file.close()
print("Team written to file.")
I would like the exported csv file to look like this:
player1,25,striker
player2,27,midfielder
and so on. However, when I check the exported csv file it looks more like this:
p
l
a
y
e
r
,
2
5
and so on.
Does anyone have an idea of where i'm going wrong?
Many thanks
Karl
Your string is a single string. It is not a list of strings. You are expecting it to be a list of strings when you are doing this:
for row in string:
When you iterate over a string, you are iterating over its characters. Which is why you are seeing a character per line.
Declare a list of strings. And append every string to it like this:
done = False
strings_list = []
while not done:
string = ""
a = input("Name of player: ")
if a == "":
done = True
else:
string += a + ','
string += input("Age: ") + ','
string += input("Position: ") + '\n'
strings_list.append(string)
Now iterate over this strings_list and print to the output file. Since you are putting the delimiter (comma) yourself in the string, you do not need a csv writer.
a_file = open(fName, 'w')
for row in strings_list:
print(row)
a_file.write(row)
a_file.close()
Note:
string is a name of a standard module in Python. It is wise not to use this as a name of any variable in your program. Same goes for your variable file