"\r\n" also not writing to next line - python

I am just following a simple Python script to write to a text file. The suggetsed method; adding "\n" to the end didn't work. It is printing within a loopAs I am using Windows, I also tried "\r\n." Still it only prints the last item. I have tried moving everything inside and outside the loop (starting with path and ending with file.close() but no go. What's going on here?
#Assign variables to the shapefiles
park = "Parks_sd.shp"
school = "Schools_sd.shp"
sewer = "Sewer_Main_sd.shp"
#Create a list of shapefile variables
shapeList = [park, school, sewer]
path = r"C:/EsriTraining/PythEveryone/CreatingScripts/SanDiegoUpd.txt"
open(path, 'w')
for shp in shapeList:
shp = shp.replace("sd", "SD")
print shp
file = open(path, 'w')
file.write(shp + "\r\n")
file.close()

Open the file outside the loop
Ex:
with open(path, "w") as infile:
for shp in shapeList:
shp = shp.replace("sd", "SD")
infile.write(shp + "\n")

You can 1) open file outside of the for loop and 2) use writelines
with open(path, 'w+') as f:
f.writelines([shp.replace("sd", "SD")+'\n' for shp in shaplist])
or
with open(path, 'w+') as f:
f.writelines(map(lambda s: s.replace("sd", "SD")+'\n', shaplist))
In this way, you open the file once and once the lines are written, the file is automatically closed (because of the [with]).

Related

Python - define a function to manage files

I need to define a fucntion that will, in short:
Open and grab the content from an existing file
Transform that content
Create a new file
Write that new content in this new file
Print the content of the new file
I'm a complete begginer, but I got this until now. How can I improve this?
def text():
#open the existing file
text_file = open('music.txt', 'r')
#reads the file
reading = text_file.read ()
#this turns everything to lower case, counts the words and displays the list vertically
from collections import Counter
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
#creates a new file and writes the content there
with open('finheiro_saida.txt', 'x') as final_file:
for i in ordem:
finheiro_saida.write(str(i) + '\n')
#not sure how to open this new file and print its content, when I tried it says the new file doesn't exist in the directory - tried everything.
final = open('C:/Users/maria/OneDrive/Documents/SD_DTM/ficheiro_saida.txt', 'r')
read_file = final.read ()
print(read_file)
You can open the new file and print its content the same way you read and wrote to it!
# ...After all your previous code...
with open('finheiro_saida.txt', 'r') as final_file:
final_file_content = final_file.read()
print(final_file_content)
Fixed some syntax error in your code.
you can display the the same way you read.
Also provide all imports to the start of the file.
you can also read all lines from the file as a list using file.readlines()
from collections import Counter
def text():
# open the existing file
text_file = open("music.txt", "r")
# reads the file
reading = text_file.read()
# this turns everything to lower case, counts the words and displays the list vertically
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
# creates a new file and writes the content there
file_name = "finheiro_saida.txt"
with open("finheiro_saida.txt", "x") as final_file:
for i in ordered_list:
final_file.write(str(i) + "\n")
return file_name
def display(final_file_name):
with open(final_file_name) as file:
print(file.read())
final_file_name = text()
display(final_file_name)

Adding notes to a data file (csv) in python

I am trying to capture data from an oscilloscope using a python script. The script saves it as in csv format. I need to add few lines of text describing the data at the beginning.
I looked at existing threads to see if there was a possible solution. I just started learning Python. I am using code that came with the instrument.
This is part of the script that saves the data as csv.
NewD = (np.insert(Wav_Data, 0, DataTime, axis = 0)).T
filename = BASE_DIRECTORY + BASE_FILE_NAME + ".csv"
now = time.time() # Only to show how long it takes to save
with open(filename, 'w') as filehandle:
np.savetxt(filename, NewD, delimiter = ',', header = column_titles)
I tried to use the section below from another code but am not sure how to append this to the csv file.
with open("notes.txt") as f:
NOTES = f.readlines()
NOTES = "".join(NOTES)
It is unable to find notes.txt which is located in the same directory as the script.
Eager to hear your feedback. Thanks in advance.
Updated to:
# Save data
NewD = (np.insert(Wav_Data, 0, DataTime, axis = 0)).T
filename = BASE_DIRECTORY + BASE_FILE_NAME + ".csv"
with open("notes.txt") as f:
NOTES = f.readlines()
NOTES = "".join(NOTES)
with open(filename, "a") as fh:
fh.write(NOTES)
now = time.time() # Only to show how long it takes to save
with open(filename, 'w') as filehandle:
np.savetxt(filename, NewD, delimiter = ',', header = column_titles)
Just open the file for appending or write
If you want to write CSV first then notes:
with open("notes.txt") as f:
NOTES = f.readlines()
NOTES = "".join(NOTES)
with open(filename, "w") as fh:
fh.write(NOTES)
# this time we give np the opened filehandle, not the filename
np.savetxt(fh, NewD, delimiter = ',', header = column_titles)

Read and write data to new file Python

I have to write substrings to a new file by reading from another file. The problem I am facing is that it only writes the last found substring.
Here is what I've tried.
def get_fasta(site):
with open('file1.txt', 'r') as myfile:
data=myfile.read()
site = site-1
str1 = data[site:site+1+20]
temp = data[site-20:site]
final_sequence = temp+str1
with open('positive_results_sequences.txt', 'w') as my_new_file:
my_new_file.write(final_sequence + '\n')
def main():
# iterate over the list of IDS
for k,v in zip(site_id_list):
get_fasta(v)
if __name__ == '__main__':
main()
That's because you've opened the inner file in w mode which recreates the file each time. So the end result is that only last write persists. You want to use a mode (which stands for "append").
Also there are some other issues with your code. For example you open and close both files in each loop iteration. You should move file opening code outside and pass them as parameters:
def main():
with open('file1.txt', 'r') as myfile:
with open('positive_results_sequences.txt', 'a') as my_new_file:
for k,v in zip(site_id_list):
get_fasta(v, myfile, my_new_file)

How to add a value to a specific line in a file in python?

I've seen really complex answers on this website as how to edit a specific line on a file but I was wondering if there was a simple way to do it?
I want to search for a name in a file, and on the line that I find that name on, I want to add an integer to the end of the line (as it is a score for a quiz). Or could you tell me how I can replace the entirety of the line with new data?
I have tried a lot of coding but either no change is made, or all of the data in the file gets deleted.
I tried this....
with open ('File.py', 'r') as class_file:
for number, line in enumerate(class_file):
if name in line:
s=open('File.py', 'r').readlines()
s[number]=str(data)
class_file=open('File.py', 'w')
class_file.writelines(new_score)
class_file.close()
As well as this function....
def replace (file, line_number, add_score):
s=open(file, 'w')
new_data=line[line_number].replace(line, add_score)
s.write(str(new_data))
s.close()
As well as this...
def replace_score(file_name, line_num, text):
new = open(file_name, 'r').readlines()
new[line_num] = text
adding_score= open(file_name, 'w')
adding_score.writelines(new)
adding_score.close()
But I still can't get it to work.
The last code works if I'm trying to replace the first line, but not the others.
You need to get the content of the file. Close the file. Modify the content and rewrite the file with the modified content. Try the following:
def replace_score(file_name, line_num, text):
f = open(file_name, 'r')
contents = f.readlines()
f.close()
contents[line_num] = text+"\n"
f = open(file_name, "w")
contents = "".join(contents)
f.write(contents)
f.close()
replace_score("file_path", 10, "replacing_text")
This is Tim Osadchiy's code:
def replace_score(file_name, line_num, text):
f = open(file_name, 'r')
contents = f.readlines()
f.close()
contents[line_num] = text+"\n"
f = open(file_name, "w")
contents = "".join(contents)
f.write(contents)
f.close()
replace_score("file_path", 10, "replacing_text")
This code does work but just remember that the line_num will always be one above the actual line number (as it is an index). So if you wanted line 9 then enter 8, not 9. Also, do not forget to put .txt at the end of the file path (I would've commented but do not have a high enough reputation)

Making a loop to write new lines to a txt file using python

I'm trying to get the script to read a text file of Congress members in which each line is formatted like this:
Darrell Issa (R-Calif)
I want it to print a line to a different file that's formatted like this (notice the added comma):
Darrell Issa,(R-Calif)
For some reason the script below works but it only does it for the first line. How do I get it to execute the loop for each line?
basicfile = open('membersofcongress.txt', 'r')
for line in basicfile:
partyst = line.find('(')
partyend = line.find(')')
party = line[partyst:partyend+1]
name = line[+0:partyst-1]
outfile = open('memberswcomma.txt','w')
outfile.write(name)
outfile.write(",")
outfile.write(party)
outfile.close()
basicfile.close()
print "All Done"
Thank you in advance for your help.
According to documentation,
'w' for only writing (an existing file with the same name will be
erased)
When you open your output file with w, loop keeps creating a new txt file for each line. Using a would be better.
basicfile = open('membersofcongress.txt', 'r')
for line in basicfile:
partyst = line.find('(')
partyend = line.find(')')
party = line[partyst:partyend+1]
name = line[+0:partyst-1]
outfile = open('memberswcomma.txt','a')
outp = name + "," + party + "\n"
outfile.write(outp)
outfile.close()
basicfile.close()
EDIT:
Much better solution would be,
You open your output file at the begining of the loop instead of inside of it.
basicfile = open('membersofcongress.txt', 'r')
outfile = open('memberswcomma.txt','w')
for line in basicfile:
partyst = line.find('(')
partyend = line.find(')')
party = line[partyst:partyend+1]
name = line[+0:partyst-1]
outp = name + "," + party + "\n"
outfile.write(outp)
outfile.close()
basicfile.close()
ok a few things to fix this, use 'a' mode to open your outfile and open it just before the loop, close the outfile after the loop and not inside it.
something like this should work (tested it)
basicfile = open('membersofcongress.txt', 'r')
outfile = open('memberswcomma.txt','a')
for line in basicfile:
partyst = line.find('(')
partyend = line.find(')')
party = line[partyst:partyend+1]
name = line[0:partyst-1]
outfile.write(name)
outfile.write(",")
outfile.write(party)
outfile.close()
basicfile.close()
print "All Done"

Categories

Resources