Print variable to txt file [duplicate] - python

This question already has answers here:
Print string to text file
(8 answers)
Closed 2 years ago.
I am working on making a separate txt file with the output data from str(velocity). Currently it prints fine in the terminal but no success in printing it to a txt file.
import socket
import numpy as np
import pigpio
#------------------------Definingfunctions and variables ------------------#
pi = pigpio.pi()
pi.set_mode(21,pigpio.INPUT)
pulseDegrees = 2*np.pi/38
T_old = 0
count = 0
def cbf(g ,L ,t):
T_new = t
global velocity, T_old
velocity = pulseDegrees/(T_new-T_old)*(1/0.000001)
print(str(velocity))
T_old = T_new
def sendData():
conn.recv (1024)
conn.send(str(velocity).encode('UTF-8'))
#--------------------------Communication--------------------#
# The units ipaddress
print ("Awaiting connection")
port=5555
s=socket.socket()
s.bind(('' ,port))
s.listen(1)
(conn,addr)=s.accept()
print ("Connected to " + str(addr))
#--------------------------Main loop--------------------#
cb = pi.callback(21,pigpio.RISING_EDGE, cbf)
while True:
sendData ()-

Use open(file, mode) with the pathname of a file as file and mode as "w" to open the file for writing. Call file. write(data) with data as the string formats "%s %d" followed by % and a tuple containing a string of the variable name, and the variable. Hope this works!

You can try
file = open("fileName.txt","w")
file.write(str(velocity) + "\n")
file.close()
"w" in line 1 means you are writing to the file. Adding "\n" means here is the end of the content.

Related

EOL while scanning string literal [in python sockets]

I'm a newbie, and this is my first question on stackoverflow, so with that said, here's my question
CLIENT CODE
import socket
cs = socket.socket()
ADDR = ('192.168.29.139',9999)
cs.connect(ADDR)
l = int(cs.recv(2048).decode())
data = cs.recv(l).decode()
data = eval(data)
cont = data["file"]["cont"]
f = open(data['file']['name'] + data['file']['ext'], "wb")
f.write(cont)
f.close()
SERVER CODE
## SERVER SIDE
import socket
ss = socket.socket()
ADDR = ('192.168.29.139',9999)
ss.bind(ADDR)
ss.listen()
conn, addr = ss.accept()
msg = input("Enter message: ")
filepath = input("Enter filepath: ")
fileName = input("Enter filename : ")
fileExt = input("Enter fileExt:" )
f = open(filepath,"rb")
r = f.read()
f.close()
fileDict = {"name": fileName, "ext": fileExt, "cont": r}
msg_dict = {"msg":msg, "file": fileDict}
msg_dict = str(msg_dict).encode()
conn.send(str(len(msg_dict)).encode())
conn.send(msg_dict)
This method works totally fine when I transfer files within the same computer (even bigger files, like several GBs, in this test I was using the windows 7 test video, that was about 25MB) but when i use it on LAN to transfer the same file, between two computers within the same network it shows an error
right during this statement
data = eval(data)
the error was, after printing so many lines of characters like \xo... and empty lines
EOL while scanning string literal ^
using pickle also gave error
Thank you for reading... Please HELP!

Cannot read data from textfile [duplicate]

This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 2 years ago.
the idea is to write a python code reading data from a text file indicated below.
https://www.minorplanetcenter.net/iau/MPCORB/CometEls.txt
Further on, I would like to filter comet-data like name magnitude etc. etc.
Right now my problem is getting data output.
My code is:
import os.path
word_dict = {}
scriptpath = os.path.dirname(__file__)
filename = os.path.join(scriptpath, 'CometEls.txt','r')
for line in filename:
line = line.strip()
relation = line.split(' ')
word_dict[relation[0]] = relation[0:20]
while True:
word = input('Comet name : ')
if word in word_dict:
print ('Comets in list :' , word_dict[word])
print(filename) #show file location
else:
print( 'No comet data!')
print(word_dict) #show data from dictionary
As you can see data in my dictionary isn't the comet-data.
It should be
Typing in "a"
Theoretically the code works, the problem is creating the dictionary?
Maybe I'm completely wrong, but it doesn't work neither with tuples or lists, or it's better to copy data into a .csv file?
Best regards
You saved the file path to the filename variable, but did not open the file for reading. You should open file, and then read it:
import os.path
word_dict = {}
scriptpath = os.path.dirname(__file__)
file_path = os.path.join(scriptpath, 'CometEls.txt')
with open(file_path, 'r') as commet_file:
for line in commet_file:
line = line.strip()
relation = line.split(' ')
word_dict[relation[0]] = relation[0:20]
while True:
word = input('Comet name : ')
if word in word_dict:
print ('Comets in list :' , word_dict[word])
print(file_path)
else:
print('No comet data!')
print(word_dict) #show data from dictionary
Also, your example has wrong margins near in while block, please check it.

How do I assign values in text file to an array inside python function and use it as global?

I am using windows10 and python 2.7.14. Running the python scripts in command prompt. I want to read some lines in text file and compare with some text, if it matches it should be stored in array. And also I want the array should be global. But In my script the I am not able to store the contents in array. How do I achieve this.
#This method is to reading logfile and saving the different datas in different lists
def Readlogs(Filename):
datafile = file(Filename)
for line in datafile:
if "login = " in line:
print(line)
trial=line
s2 = "= "
ArrayLogin = trial[trial.index(s2) + len(s2):]
print(ArrayLogin)
print(ArrayLogin)
if "Overlay = " in line:
print(line)
trial2=line
s2 = "= "
arrayOverlay = trial2[trial2.index(s2) + len(s2):]
print(arrayOverlay)
Readlogs(WriteFileName)
You can declare empty arrays and append items to it.
#This method is to reading logfile and saving the different datas in different lists
def Readlogs(Filename):
#empty array
ArrayLogin, arrayOverlay = [], []
datafile = file(Filename)
for line in datafile:
if "login = " in line:
print(line)
trial=line
s2 = "= "
ArrayLogin.append(trial[trial.index(s2) + len(s2):])
print(ArrayLogin)
print(ArrayLogin)
if "Overlay = " in line:
print(line)
trial2=line
s2 = "= "
arrayOverlay.append(trial2[trial2.index(s2) + len(s2):])
print(arrayOverlay)
return ArrayLogin, arrayOverlay
arr1, arr2, = Readlogs(WriteFileName)

I want to save python variable result to a file [duplicate]

This question already has answers here:
Python 2.7: Print to File
(6 answers)
Closed 6 years ago.
when this files run gives corresponding output values as;
# test BLE Scanning software
# jcs 6/8/2014
import MySQLdb as my
import blescan
import sys
import bluetooth._bluetooth as bluez
dev_id = 0
db = my.connect(host="localhost",
user="root",
passwd="root",
db="test"
)
cursor = db.cursor()
try:
sock = bluez.hci_open_dev(dev_id)
print "ble thread started"
except:
print "error accessing bluetooth device..."
sys.exit(1)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
while True:
returnedList = blescan.parse_events(sock, 10)
print "----------"
for beacon in returnedList:
print beacon
sql = "insert into beacon VALUES(null, '%s')" % \
(beacon)
number_of_rows = cursor.execute(sql)
db.commit()
db.close()
I want output stored in a text file
cf:68:cc:c7:33:10,b9407f30f5f8466eaff925556b57fe6d,13072,52423,-74,-78
cf:68:cc:c7:33:10,74696d6f74650e160a181033c7cc68cf,46608,13255,-52,-77
da:f4:2e:a0:70:b1,b9407f30f5f8466eaff925556b57fe6d,28849,11936,-74,-79
da:f4:2e:a0:70:b1,74696d6f74650e160a18b170a02ef4da,46769,28832,46,-78
dd:5d:d3:35:09:dd,8aefb0316c32486f825be26fa193487d,1,1,-64,-78
c3:11:48:9b:cf:fa,8aefb0316c32486f825be26fa193487d,0,0,-64,-73
fd:5b:12:7f:02:e4,b9407f30f5f8466eaff925556b57fe6d,740,4735,-74,-79
fd:5b:12:7f:02:e4,74696d6f74650e160a18e4027f125bfd,46820,639,18,-80
dd:5d:d3:35:09:dd,8aefb0316c32486f825be26fa193487d,1,1,-64,-77
so on... and then write store these values in text file. For text file, is it possible to generate text file as a part of script? Thanks
if what you want is to store the data in file, so you can open it later the simplest way is to use the Pickle (or the cPickle) module
something like:
import cPickle
#store the data in file
with open('/path/to/file.txt', 'wb') as f:
cPickle.dump(returnedList, f)
#to read the data
loaded_returnedList = cPickle.load(open('/path/to/file.txt'))
print loaded_returnedList == returnedList # Prints True
now if what you want is store the data for visual store (maybe to open it in excel later), the csv module is for you
import csv
with open('/path/to/file', 'w') as f:
writer = csv.writer(f)
for beacon in returnedList:
writer.writerow(beacon)
Try this for your loop
while True:
returnedList = blescan.parse_events(sock, 10)
print "----------"
f = open('bluez.txt', 'a+')
for beacon in returnedList:
print beacon
f.write(','.join(beacon)+'\n')
f.close()
EDIT: now appending mode

ping using python and save to a file [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 6 years ago.
Ping_Python
Below is Code to ping hosts and create a CSV file out of the results.
import os
for i in range (0,255):
for j in range(1,254):
hostname = "10.222.{0}.{1}".format(i,j)
response = os.system ("ping -n 1 " + hostname)
if response == 0:
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
fp.writelines(hostname + "host up\n")
else:
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
fp.write(hostname + "host dead\n")
This code allows me to ping hosts,but while writing the results to a CSV, it overwrites the previously written result and only writes penultimate or unltimate result.
Change both of
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'w')
to
fp = open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'a')
in order to open the file in append mode.
You can also improve your code by using with, so you don't open the file every iteration:
import os
with open("C:\\Users\\anudeepa\\Desktop\\hostname.csv", 'a') as fp:
for i in range (0,255):
for j in range(1,254):
hostname = "10.222.{0}.{1}".format(i,j)
response = os.system ("ping -n 1 " + hostname)
if response == 0:
fp.writelines(hostname + "host up\n")
else:
fp.write(hostname + "host dead\n")
This will also have the benefit of closing the file when the script ends.

Categories

Resources