I want to replace a whole line in a text document, if there is a line that begins with "truck_placement"
Can I remove the whole line when it contains "truck_placement" and then write the new text?
I tried it but it only inserts the new text und doesn't replace the whole line.
Thats the current code:
cordget = coordinatesentry.get()
fin = open(save_file,"r")
filedata = fin.read()
fin.close
newdata = filedata.replace("truck_placement: " , "truck_placement: " + cordget)
fin = open(save_file, "w")
fin.write(newdata)
fin.close
Your best bet is to append all the lines without "truck_placement" to a new file. This can be done with the following code:
original = open("truck.txt","r")
new = open("new_truck.txt","a")
for line in original:
if "truck_placement" not in line:
new.write(line)
original.close()
new.close()
You can either read the whole file into one string and replace the line using regular expression:
import re
cordget = "(value, one) (value, two)"
save_file = "sample.txt"
with open(save_file, "r") as f:
data = f.read()
# Catch the line from "truck_placement: " until the newline character ('\n')
# and replace it with the second argument, where '\1' the catched group
# "truck_placement: " is.
data = re.sub(r'(truck_placement: ).*\n', r'\1%s\n' % cordget, data)
with open(save_file, "w") as f:
f.writelines(data)
Or you could read the file as a list of all lines and overwrite the specific line:
cordget = "(value, one) (value, two)"
save_file = "sample.txt"
with open(save_file, "r") as f:
data = f.readlines()
for index, line in enumerate(data):
if "truck_placement" in line:
data[index] = f"truck_placement: {cordget}\n"
with open(save_file, "w") as f:
f.writelines(data)
I have a folder full of .mpt files, each of them having the same data format.
I need to delete the first 57 lines from all files and append these files into one csv - output.csv.
I have that section already:
import glob
import os
dir_name = 'path name'
lines_to_ignore = 57
input_file_format = '*.mpt'
output_file_name = "output.csv"
def convert():
files = glob.glob(os.path.join(dir_name, input_file_format))
with open(os.path.join(dir_name, output_file_name), 'w') as out_file:
for f in files:
with open(f, 'r') as in_file:
content = in_file.readlines()
content = content[lines_to_ignore:]
for i in content:
out_file.write(i)
print("working")
convert()
print("done")
This part works ok.
how do i add the filename of each .mpt file as the last column of the output.csv
Thank you!
This is a quick 'n dirty solution.
In this loop the variable i is just a string (a line from a CSV file):
for i in content:
out_file.write(i)
So you just need to 1) strip off the end of line character(s) (either "\n" or "\r\n") and append ",".
If you're using Unix, try:
for i in content:
i = i.rstrip("\n") + "," + output_file_name + "\n"
out_file.write(i)
This assumes that the field separator is a comma. Another option is:
for i in content:
i = i.rstrip() + "," + output_file_name
print >>out_file, i
This will strip all white space from the end of i.
Add quotes if you need to quote the output file name:
i = i.rstrip(...) + ',"' + output_file_name '"'
The relevant part:
with open(f, 'r') as in_file:
content = in_file.readlines()
content = content[lines_to_ignore:]
for i in content:
new_line = ",".join([i.rstrip(), f]) + "\n" #<-- this is new
out_file.write(new_line) #<-- this is new
I have one problem. I have some data file which structure is that:
first line
219,241,280,369,402.7,472.7,520,553.3,588.7,635.3,678.7,734.7,795.3,880,914,968.7,1030.7,1085.3,1185.3
second line
436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7
In first line are values of x and in second line are values of y.
Now I want these values to get into this shape:
x=r_[219,241,280,369,402.7,472.7,520,553.3,588.7,635.3,678.7,734.7,795.3,880,914,968.7,1030.7,1085.3,1185.3]
y=r_[436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7]
I have a problem with the addition of r_.
Any suggestion?
Well, if I understand this correctly this is what you should do (assuming the name of the file is test.txt):
with open("test.txt", "r") as f:
firstline = f.readline().rstrip("\n")
secondline = f.readline().rstrip("\n")
firstline = "x=r_[" + firstline + "]\n"
secondline = "y=r_[" + secondline + "]\n"
data = firstline+secondline
with open("test2.txt", "w") as f: # <-- changed name here, just in case
f.write(data)
Quick answer:
firstline = '436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7'
secondline = '436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7'
x = 'r_[' + firstline + ']'
y = 'r_[' + secondline + ']'
I really have no idea what you actually want...
I have the codez:
import re
pattern = ','
firstNames = "dictionary//first_names.txt"
new_file = []
def openTxtFile(txtFile):
file = open (txtFile,"r")
data = file.read()
print (data)
file.close
def parseTextFile(textFile):
openTxtFile(firstNames)
for line in lines:
match = re.search(pattern, line)
if match:
new_line = match.group() + '\n'
print (new_line)
new_file.append(new_line)
with open(firstNames, 'w') as f:
f.seek(0)
f.writelines(new_file)
I am trying to take the original file, match it on a "," and return line by line to a New file the string before the "," I'm having trouble putting all this together, thanks!
Use the csv module, since your original file is comma separated:
import csv
with open('input_file.txt') as f:
reader = csv.reader(f)
names = [line[0] for line in reader]
with open('new_file.txt','w') as f:
for name in names:
f.write('{0}\n'.format(name))
I am trying to convert a csv file into another file (file type doesn't matter as the program using the converted data just opens it like a text file).
So far I have managed to convert and print the original csv data into the the data structure I want but I now need to save that as another file.
import csv
file = open('newData', 'w')
with open('initialData.csv', 'rb') as f:
reader = csv.reader(f, delimiter=',', quotechar='|')
for row in reader:
print row[13] + ' 1:' + row[0] + ' 2:' + row[1]
file.write(f)
file.close()
Whenever I run this I get the error:
TypeError: expected a character buffer object
I know there is nothing wrong with converting the csv file as that prints fine when I comment out the file.write(f).
Many thanks in advance!
Why are you trying to write the original file (the f object) to the new file? Don't you want to write the re-formatted data?
import csv
with open('initialData.csv', 'rb') as f_in, open('newData', 'w') as f_out:
reader = csv.reader(f_in, delimiter=',', quotechar='|')
for row in reader:
print row[13] + ' 1:' + row[0] + ' 2:' + row[1]
f_out.write(row[13] + ' 1:' + row[0] + ' 2:' + row[1])
Edit: as suggested by Jon Clements, use context manager for output as well + indentation fix.
You're trying to print out the file handle for the whole csv file. I'm guessing you want the text you're printing to be written out into a file, in that case just do:
with open('initialData.csv', 'rb') as infile, open('newData.txt') as outfile:
reader = csv.reader(infile, ...)
for row in reader:
outfile.write(row[13] + ' 1:' + row[0] + ' 2:' + row[1])