when i m printing data from my json file to csv file it is not getting printed in diff columns..
here is my code
import json
import urllib
import csv
def main():
f1 = open('tweet-stream.json','r')
Outputfile =open('newdata3.csv', 'w')
count = 0
for line in f1:
d = json.loads(line)
lang = d["user"]["lang"]
status_count = d["user"]["statuses_count"]
print >>Outputfile,"Language: " + lang + "Status_Count" +str(status_count)
if __name__ == "__main__":
main()
f1 = json.load(open(tweet-stream.json', 'r'))
fileWriter = csv.writer(file1 , delimiter=",",quotechar='"', quoting=csv.QUOTE_MINIMAL)
for x in f1:
temp = [x["user"]["lang"],x["user"]["statuses_count"]]
fileWriter.writerow(temp)
file1.close()
Related
I wanted to store some value in a json file
json file gets readed but not getting writed
import json
import os
filepath = os.path.abspath(__file__).replace("test.py", "test.json")
data = json.load(open(filepath, "r"))
out_file = open("test.json", "w")
a = input()
data["cool"] = a
print(data)
json.dump(data,out_file, indent = 6)
out_file.close()
Hi I am using this method to write a csv file from a csv file which is a hashed code but i only receive the last row in output, how can i add each row to the previous one?
import hashlib
import csv
d = dict()
result = ()
for i in range(0 , 9999) :
n = hashlib.sha256(str(i).encode())
d[n.hexdigest()] = str(i)
with open('/Users/MJ-Mac/Desktop/karname.txt') as f:
file = csv.reader(f)
for row in file :
a = row[0]
b = d[row[1]]
result = (a , b)
with open('/Users/MJ-Mac/Desktop/result3.txt', 'w') as f2:
file2 = csv.writer(f2)
file2.writerow(result)
Other answers have suggested replacing 'w' with 'a', this is not necessary when working with csv.writer. It also could make your file grow everytime you run the program.
Instead of reopening and closing relut3.txt, keep it open and use just one writer
import hashlib
import csv
d = dict()
result = ()
for i in range(0 , 9999) :
n = hashlib.sha256(str(i).encode())
d[n.hexdigest()] = str(i)
with open('/Users/MJ-Mac/Desktop/result3.txt', 'w') as result_file:
result_writer = csv.writer(result_file) # only create this once
with open('/Users/MJ-Mac/Desktop/karname.txt') as f:
file = csv.reader(f)
for row in file :
a = row[0]
b = d[row[1]]
result = (a , b)
result_writer.writerow(result) # use the already created writer
Your code is writing one line to the file, then it opens the file again and writes the next line as the full content of the program.
So on the second run through the loop only the second line will be in the file.
import hashlib
import csv
d = dict()
result = ()
for i in range(0 , 9999) :
n = hashlib.sha256(str(i).encode())
d[n.hexdigest()] = str(i)
with open('/Users/MJ-Mac/Desktop/karname.txt') as f:
file = csv.reader(f)
for row in file :
a = row[0]
b = d[row[1]]
result = (a , b)
with open('/Users/MJ-Mac/Desktop/result3.txt', 'a') as f2:
file2 = csv.writer(f2)
file2.writerow(result)
It might be better to open the file and then write everything to it:
import hashlib
import csv
d = dict()
result = ()
for i in range(0 , 9999) :
n = hashlib.sha256(str(i).encode())
d[n.hexdigest()] = str(i)
with open('/Users/MJ-Mac/Desktop/karname.txt') as f:
file = csv.reader(f)
with open('/Users/MJ-Mac/Desktop/result3.txt', 'w') as f2:
file2 = csv.writer(f2)
for row in file :
a = row[0]
b = d[row[1]]
result = (a , b)
file2.writerow(result)
I can't run this myself, since your data is not included.
However, I think your problem is that with open('/Users/MJ-Mac/Desktop/result3.txt', 'w') has the "w" flag -- which stands for "write" -- so your data is being overwritten, You might instead need the "a" flag for "append," so that each line will be appended to the data you are exporting.
import hashlib
import csv
d = dict()
result = ()
for i in range(0 , 9999) :
n = hashlib.sha256(str(i).encode())
d[n.hexdigest()] = str(i)
with open('/Users/MJ-Mac/Desktop/karname.txt') as f:
file = csv.reader(f)
for row in file :
a = row[0]
b = d[row[1]]
result = (a , b)
with open('/Users/MJ-Mac/Desktop/result3.txt', 'a') as f2:
file2 = csv.writer(f2)
file2.writerow(result)
It is easier and more readable to open both the input and output files at once, and initialise the CSV reader and writer at the start:
with open('/Users/MJ-Mac/Desktop/karname.txt') as in_file, open('/Users/MJ-Mac/Desktop/result3.txt', 'w') as out_file:
output = csv.writer(out_file)
for row in csv.reader(in_file):
output.writerow([row[0], d[row[1]])
I am reading file in binary mode using python and it is working perfectly. I tried to update the content and the save it into a new file. The code's below:
def main():
f = open("inputFile", "rb")
myFile = f.read()
outFile = myFile
for i in range(0, len(myFile)):
d1 = myFile[i] + 1
outFile[i] = d1
f2 = open("otFile", "wb")
f2.write(outFile)
f2.close()
The error is:
outFile[i] = d1
TypeError: 'bytes' object does not support item assignment
I tried
outFile[i] = bytes(d1)
I've got this error:
TypeError: 'bytes' object does not support item assignment
Use bytearray() to convert the infile which gives the functionality of both reading and writing as well
def main():
f = open("infile", "rb")
myFile = f.read()
outFile = bytearray(myFile)
for i in range(0, len(myFile)):
d1 = myFile[i] + 1
outFile[i] = d1
f2 = open("outfile", "wb")
f2.write(outFile)
f2.close()
I think you can just to something like this:
def main():
f = open("inputFile", "rb")
myFile = f.read()
f.close()
outFile = myFile
for i in range(0, len(myFile)):
d1 = myFile[i] + 1
outFile += bytes(d1)
f2 = open("otFile", "wb")
f2.write(outFile)
f2.close()
main()
I am new to python. trying to write a program to read a file1 and write in file2
Ex: file1 contents
a=value1
b=value2
c=dddd.eeeee.fffff
d=value4
need to fetch the value of variable c and write in file2
file2 contents
(suiteName: "aaaa.bbbb.ccc")
i need to replace the value of suiteNmae: "aaaa.bbbb.ccc" with c i.e, file 2 suitename should replace with c value suiteName: dddd.eeeee.fffff
This should be done using python file2 other values should not be changed
import os
import sys
import csv
file_path = "C:/Users/file1"
replace_file_path = "C:/Users/file2"
def get_c(file_name):
with open(file_name, 'r') as f:
fileone = csv.reader(f,delimiter='=')
for row in fileone:
if row[0] == 'c':
return row[1]
def get_suiteName(file_name):
with open(file_name, 'r') as f1:
filetwo = csv.reader(f1,delimiter=':')
for row in filetwo:
if row[0] == 'suiteName':
return row[1]
After this I am confused and this is also giving error
In [102]: with open("file1.txt") as f1, open("file2.txt") as f2:
...: f1_value = [i.strip().split("=")[1] for i in f1.readlines() if i.strip().split("=")[0] == "c"][0]
...: f2_value = re.sub(r"suiteName: \"(.*)\"", "suiteName: \"{}\"".format(f1_value), f2.read())
...: print(f2_value)
...: with open("file2.txt","w") as f3:
...: f3.write(f2_value)
...:
override func broadcastStarted(withSetupInfo setupInfo: [String : NSObject]?) {
if let userDefaults = UserDefaults(suiteName: "dddd.eeeee.fffff")
check output directory(outputfile) before running the code to check the file already in there!
import os
texttofind ='abcd'
texttoreplace ='wxyz'
sourcepath = os.listdir('inputfiles/')
for file in sourcepath:
inputfile = 'inputfiles/'+ file
print('conversion is ongoing for:' +inputfile)
with open(inputfile,'r') as inputfile:
filedata = inputfile.read()
freq = 0
freq = filedata.count(texttofind)
destinationpath = 'outputfile/' + file
filedata = filedata.replace(texttofind,texttoreplace)
with open(destinationpath,'w') as file:
file.write(filedata)
print ('total %d Record replaced %freq')
Something like this?
import os
texttofind ='abcd'
texttoreplace ='wxyz'
sourcepath = os.listdir('inputfiles/')
for file in sourcepath:
destinationpath = 'outputfile/' + file
if not os.path.isfile(destinationpath):
inputfile = 'inputfiles/'+ file
print('conversion is ongoing for:' +inputfile)
with open(inputfile,'r') as inputfile:
filedata = inputfile.read()
freq = 0
freq = filedata.count(texttofind)
filedata = filedata.replace(texttofind,texttoreplace)
with open(destinationpath,'w') as file:
file.write(filedata)
print ('total %d Record replaced %freq')