I have a file I am reading from.
I need to output a copy of the file where line numbers are simply appended to the end of each line.
I tried the following code but couldn't get it to work:
with open('s.txt', 'r') as f, open("1.txt", "w") as out:
abc_list = [[float(n) for n in line.split()] for line in f]
for i,line in enumerate(abc_list):
out.write('{i+0:2}\n'.format(line.rstrip('\n')))
The input-file contains data similar to the following:
1 2
5 6
25 85
The shows what the contents of the output file should be:
1 2 1
5 6 2
25 85 3
I got the following error:
AttributeError: 'list' object has no attribute 'rstrip'
You don't need to call line.rstrip(). At that point line is a list of numbers, not a line from the input file. You should loop over the numbers and write each of them without a newline.
Then write i to the file at the end of the line.
If you want the line numbers to start at 1, use that as an argument to enumerate().
with open('s.txt', 'r') as f, open("1.txt", "w") as out:
abc_list = [[float(n) for n in line.split()] for line in f]
for i,nums in enumerate(abc_list, 1):
for n in nums:
out.write(str(n) + ' ')
out.write('{i:2}\n'.format(i))
You can also avoid creating the list of all lines.
with open('s.txt', 'r') as f, open("1.txt", "w") as out:
for i, line in enumerate(f, 1):
nums = [float(n) for n in line.split()]
for n in nums:
out.write(str(n) + ' ')
out.write('{i:2}\n'.format(i))
i got KeyError: 'i' with the answer of Barmar .. i fixed it now. Thanks for the help
with open('s.txt', 'r') as f, open("1.txt", "w") as out:
for i, line in enumerate(f, 1):
nums = [float(n) for n in line.split()]
for n in nums:
out.write(str(n) + ' ')
out.write(f'{i+0:2}\n')
The following function will append line numbers to the end of every line of a file:
def get_suffixed_iterator(rf, sep =" "):
sep = str(sep)
rf = iter(rf)
rf = map(str, rf)
rf = map(str.strip, rf)
for num, text in enumerate(rf, 1):
yield text + sep + str(num)
Below, we test the function:
f = ["orange\n\n", "eggs", "\n\napple\n\n\n"]
for lin in get_suffixed_iterator(f):
print(lin)
with open('readme.txt', 'r') as rf, open("writeme.txt", "w") as wf:
it = append_line_numbers(rf)
for line in it:
print(line, file=wf, end="\n")
Related
So let's say I have a text file, which contains this:
a
b
c
d
e
I want to iterate through every line of this file, but in the process also get the line following the first line. I have tried this:
with open(txt_file, "r") as f:
for line1, line2 in itertools.zip_longest(*[f] * 2):
if line2 != None:
print(line1.rstrip() + line2.rstrip())
else:
print(line1.rstrip())
which returns something like:
ab
cd
e
However, I would like to have output like this:
ab
bc
cd
de
e
Anyone have an idea for how to accomplish this? Thanks in advance!
Why iterator? Simply cache one line:
with open("t.txt","w") as f:
f.write("a\nb\nc\nd\ne")
with open("t.txt", "r") as f:
ll = next(f) # get the first line
for line in f: # get the remaining ones
print(ll.rstrip() + line.rstrip())
ll = line # cache current line as last line
print(ll) # get last one
Output:
ab
bc
cd
de
e
with open(txt_file, "r") as f:
last = None
for line in f:
if not last is None:
print(last + line.rstrip())
last = line.rstrip()
# print the last line
print line.rstrip()
A simple solution would be:
with open(txt_file, "r") as f:
content = f.read().splitlines()
for i, line in enumerate(content):
if i == len(content) - 1:
print(line)
else:
print(line + content[i+1])
You can also create a generator which takes an iterable as an input parameter and yields tuples of (previous_element, element).
def with_previous(iterable):
iterator = iter(iterable)
previous_element = next(iterator)
for element in iterator:
yield previous_element, element
previous_element = element
You need to handle the special cases if the iterable contains only one or two elements.
I have a file and it contain a thousands values so i wont to read only the first 10 and the last 10 values
So I used v.readline()
And v.read() but it didn’t give me the solution
Iterate over the file using next function.
with open("file") as f:
lines = [next(f) for x in range(10)]
Simply printing:
res=[]
with open('filename.txt') as inf:
for count, line in enumerate(inf, 1):
res.append(str(count))
for r in range(10):
print(res[r])
for r in range(count-10,count):
print(res[r])
Alternatively, this saves the output as variable ‘result’:
res=[]
result=''
with open('filename.txt') as inf:
for count, line in enumerate(inf, 1):
res.append(str(count))
for r in range(10):
result = result + '\n' + res[r]
for r in range(count-10,count):
result = result + '\n' + res[r]
print(result)
I'd like to join every 4th line together so I thought something like this would work:
import csv
filename = "mycsv.csv"
f = open(filename, "rb")
new_csv = []
count = 1
for i, line in enumerate(file(filename)):
line = line.rstrip()
print line
if count % 4 == 0:
new_csv.append(old_line_1 + old_line_2 + old_line_3+line)
else:
old_line_1 = line[i-2]
old_line_2 = line[i-1]
old_line_3 = line
count += 1
print new_csv
But line[i-1] and line[i-2] does not take current line -1 and -2 as I thought. So how can I access current line -1 and -2?
The variable line contains only the line for the current iteration, so accessing line[i-1] will only give you one character within the current line. The other answer is probably the tersest way to put it but, building on your code, you could do something like this instead:
import csv
filename = "mycsv.csv"
with open(filename, "rb") as f:
reader = csv.reader(f)
new_csv = []
lines = []
for i, line in enumerate(reader):
line = line.rstrip()
lines.append(line)
if (i + 1) % 4 == 0:
new_csv.append("".join(lines))
lines = []
print new_csv
This should do as you require
join_every_n = 4
all_lines = [line.rstrip() for line in file(filename)] # note the OP uses some unknown func `file` here
transposed_lines = zip(*[all_lines[n::join_every_n] for n in range(join_every_n)])
joined = [''.join([l1,l2,l3,l4]) for (l1,l2,l3,l4) in transposed_lines]
likewise you could also do
joined = map(''.join, transposed_lines)
Explanation
This will return every i'th element in a your_list with an offset of n
your_list[n::i]
Then you can combine this across a range(4) to generate for every 4 lines in a list such that you get
[[line0, line3, ...], [line1, line4, ...], [line2, line6, ...], [line3, line7, ...]]
Then the transposed_lines is required to transpose this array so that it becomes like
[[line0, line1, line2, line3], [line4, line5, line6, line7], ...]
Now you can simple unpack and join each individual list element
Example
all_lines = map(str, range(100))
transposed_lines = zip(*[all_lines[n::4] for n in range(4)])
joined = [''.join([l1,l2,l3,l4]) for (l1,l2,l3,l4) in transposed_lines]
gives
['0123',
'4567',
'891011',
...
This is what I have to do:
Read content of a text file, where two numbers separated by comma are on each line (like 10, 5\n, 12, 8\n, …)
Make a sum of those two numbers
Write into new text file two original numbers and the result of summation = like 10 + 5 = 15\n, 12 + 8 = 20\n, …
So far, I've got this:
import os
import sys
relative_path = "Homework 2.txt"
if not os.path.exists(relative_path):
print "not found"
sys.exit()
read_file = open(relative_path, "r")
lines = read_file.readlines()
read_file.close()
print lines
path_output = "data_result4.txt"
write_file = open(path_output, "w")
for line in lines:
line_array = line.split()
print line_array
You need to have a good understanding of python to understand this.
First, read the file, and get all of the lines by splitting it with a line feed (\n)
For each expression, calculate the answer and write it. Remember, you need to cast the numbers to integers so that they can be added together.
with open('Original.txt') as f:
lines = f.read().split('\n')
with open('answers.txt', 'w+') as f:
for expression in lines: # expression should be in format '12, 8'
nums = [int(i) for i in expression.split(', ')]
f.write('{} + {} = {}\n'.format(nums[0], nums[1], nums[0] + nums[1]))
# That should write '12 + 8 = 20\n'
Make your last for loop look like this:
for line in lines:
splitline = line.strip().split(",")
summation = sum(map(int, splitline))
write_file.write(" + ".join(splitline) + " = " + str(summation) + "\n")
One beautiful thing about that way is that you can have as many numbers as you want on a line, and it will still display correctly.
Seems like the input File is csv so just use the csv reader module in python.
Input File Homework 2.txt
1, 2
1,3
1,5
10,6
The script
import csv
f = open('Homework 2.txt', 'rb')
reader = csv.reader(f)
result = []
for line in list(reader):
nums = [int(i) for i in line]
result.append(["%(a)s + %(b)s = %(c)s" % {'a' : nums[0], 'b' : nums[1], 'c' : nums[0] + nums[1] }])
f = open('Homework 2 Output.txt', 'wb')
writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for line in result:
writer.writerow(line)
The output file is then Homework 2 Output.txt
1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
10 + 6 = 16
I want use python to read specific multiply lines from txt files. For example ,read line 7 to 10, 17 to 20, 27 to 30 etc.
Here is the code I write, but it will only print out the first 3 lines numbers. Why? I am very new to use Python.
with open('OpenDR Data.txt', 'r') as f:
for poseNum in range(0, 4):
Data = f.readlines()[7+10*poseNum:10+10*poseNum]
for line in Data:
matAll = line.split()
MatList = map(float, matAll)
MatArray1D = np.array(MatList)
print MatArray1D
This simplifies the math a little to choose the relevant lines. You don't need to use readlines().
with open('OpenDR Data.txt', 'r') as fp:
for idx, line in enumerate(fp, 1):
if idx % 10 in [7,8,9,0]:
matAll = line.split()
MatList = map(float, matAll)
MatArray1D = np.array(MatList)
print MatArray1D
with open('OpenDR Data.txt') as f:
lines = f.readlines()
for poseNum in range(0, 4):
Data = lines[7+10*poseNum:10+10*poseNum]
You should only call readlines() once, so you should do it outside the loop:
with open('OpenDR Data.txt', 'r') as f:
lines = f.readlines()
for poseNum in range(0, 4):
Data = lines[7+10*poseNum:10+10*poseNum]
for line in Data:
matAll = line.split()
MatList = map(float, matAll)
MatArray1D = np.array(MatList)
print MatArray1D
You can use a combination list slicing and comprehension.
start = 7
end = 10
interval = 10
groups = 3
with open('data.txt') as f:
lines = f.readlines()
mult_lines = [lines[start-1 + interval*i:end + interval*i] for i in range(groups)]
This will return a list of lists containing each group of lines (i.e. 7 thru 10, 17 thru 20).