write and save a txt file using spyder - python

I am trying to write a txt file from Python:
for i in range(len(X)):
k+=1
g.write('CoordinatesX='+str(i)+str(X[i])+'\n')
g.write('D'+str(k)+'#Sketch'+str(sketch_number)+'=CoordinatesX'+str(k)+'\n')
k+=1
g.write('CoordinatesY='+str(i)+str(Y[i])+'\n')
g.write('D'+str(k)+'#Sketch'+str(sketch_number)+'=CoordinatesY'+str(k)+'\n')
k+=1
g.write('CoordinatesZ='+str(i)+str(Z[i])+'\n')
g.write('D'+str(k)+'#Sketch'+str(sketch_number)+'=CoordinatesZ'+str(k)+'\n')
g.close()
I get no error, but then when I go to look for the downloaded file, I don't find it, and nothing was written.
Does someone know what I am doing wrong? Thank you so much already.
cheers!

In Python you can open a file this way:
file = open('file.txt', 'r+')
file.read() # This will return the content
file.write("This file has just been overwritten")
file.close() # This will close the file
A better practice is to use the with/as syntax:
with open('file.txt', 'r+') as file:
file.read()
file.write("This file has just been overwritten")
# The file is automatically closed (saved) after the with block has ended

Related

Python Read range of lines from txt on a server and write them to local file

I have a log file on a remote server and I want to write to a file the lines i have chosen to write.
The thing is that print(linex) below is OK and I see all lines in CMD console.
But it is writing only the 1st line to the file.
What am I missing here...?
def GetEndLastLine ():
last_line = sum(1 for line in open('//10.10.10.10/d$/log/server.log'))
print(last_line)
with open('//10.10.10.10/d$/log/server.log') as f:
for linex in itertools.islice(f, first_line, last_line):
break
x = open(r"LogFile.txt", "w")
print(linex)
x.write("LOGS START HERE****\n\n"+ output +"")
os.system("start notepad++.exe LogFile.txt")
This should write the entire content of server.log to your local LogFile.txt.
with open('//10.10.10.10/d$/log/server.log') as f:
lines = f.readlines()
with open("LogFile.txt", "w") as f:
f.writelines(lines)
Thanks for the help- opening a new thread for the other issue which is different

How to open and print the contents of a file line by line using subprocess?

I am trying to write a python script which SSHes into a specific address and dumps a text file. I am currently having some issues. Right now, I am doing this:
temp = "cat file.txt"
need = subprocess.Popen("ssh {host} {cmd}".format(host='155.0.1.1', cmd=temp),shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print(need)
This is the naive approach where I am basically opening the file, saving its output to a variable and printing it. However, this really messes up the format when I print "need". Is there any way to simply use subprocess and read the file line by line? I have to be SSHed into the address in order to dump the file otherwise the file will not be detected, that is why I am not simply doing
f = open(temp, "r")
file_contents = f.read()
print (file_contents)
f.close()
Any help would be appreciated :)
You don't need to use the subprocess module to print the entire file line by line. You can use pure python.
f = open(temp, "r")
file_contents = f.read()
f.close()
# turn the file contents into a list
file_lines = file_contents.split("\n")
# print all the items in the list
for file_line in file_lines:
print(file_line)

Python wont write text file

I write:
f = open("Textfile.txt","w")
f.write("This is a text file")
f.close()
But when i open the text file nothing has been written, does anybody know why?
using it in a with statement should handle the closing of the file for you. Does this solve the problem?
with open('Textfile.txt','w') as f:
f.write('This is a text file')
To save a file at the desired location use the full path.
with open('/home/me/project/testfile.txt', 'w') as outfile:
outfile.write('content')
If you want to save your file in the same directory as your script you can use __file__.
import os.path
path_of_script = os.path.dirname(__file__)
with open(os.path.join(path_of_script, 'testfile.txt', 'w') as outfile:
outfile.write('content')

Read txt files, results in empty lines

I have some problem to open and read a txt-file in Python. The txt file contains text (cat text.txt works fine in Terminal). But in Python I only get 5 empty lines.
print open('text.txt').read()
Do you know why?
I solved it. Was a utf-16 file.
print open('text.txt').read().decode('utf-16-le')
if this prints the lines in your file then perhaps the file your program is selecting is empty? I don't know, but try this:
import tkinter as tk
from tkinter import filedialog
import os
def fileopen():
GUI=tk.Tk()
filepath=filedialog.askopenfilename(parent=GUI,title='Select file to print lines.')
(GUI).destroy()
return (filepath)
filepath = fileopen()
filepath = os.path.normpath(filepath)
with open (filepath, 'r') as fh:
print (fh.read())
or alternatively, using this method of printing lines:
fh = open(filepath, 'r')
for line in fh:
line=line.rstrip('\n')
print (line)
fh.close()
or if you want the lines loaded into a list of strings:
lines = []
fh = open(filepath, 'r')
for line in fh:
line=line.rstrip('\n')
lines.append(line)
fh.close()
for line in lines:
print (line)
When you open file I think you have to specify how do you want to open it. In your example you should open it for reading like:
print open('text.txt',"r").read()
Hope this does the trick.

How can i save this into a variable so that i can save it to a file

I have a bit of code which prints what I want to save but I cant save it as a variable because of the format. Please can you show me how to save this as a variable so that I can save it into a file
It wont let me add a picture but this is what I want to add to a variable (What its printing)
print(text[i],end="")
x = text[i]
with open("output.txt", 'w') as f:
f.write(x)
or
with open("output.txt", 'w') as f:
f.write(text[i])
Open a file:
f = open('filename','w')
Write a line of text to the file:
f.write(text[i])
And finally close the file:
f.close()

Categories

Resources