This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 1 year ago.
I'm trying to get a python script working that will take an .txt file with number inputs
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
and turn it into
Hello 10 and 11 and 12 and 13....
and after x numbers it should start again like
Hello 10 and 11 and 12 and 13
Hello 14 and 15 and 16 and 17
Hello 18 ....
what ive got is this
def idcommands(contentsplit):
command = ' and '.join(contentsplit)
textfile = open('command.txt', 'w')
textfile.write("Hello " +command)
textfile.close()
def main():
file = open("ids.txt", "r")
content = file.read()
contentsplit = content.split(' ')
file.close()
idcommands(contentsplit)
So it will do it all in one line but I don't know how to split after x numbers.
It's not clear if you want a separate file for each line or one file for them all.
This code will create one file.
def idcommands(contentsplit, n = 4):
commands = ['Hello ' + ' and '.join(contentsplit[idx:idx+n]) for idx in range(0, len(contentsplit), n)]
with open('command.txt', 'w') as textfile:
textfile.write('\n'.join(commands))
def main():
file = open("ids.txt", "r")
content = file.read()
contentsplit = content.split(' ')
file.close()
idcommands(contentsplit, 2)
main()
Related
i want to print in the even file all even numbers with spaces between them eg: 12 6 20 10 not 1262010 with no spaces in front or back. How can i do this?
def write_positive_even_to_file(filename):
with open(filename, 'r') as orginal, open('xxx.txt', 'a') as even:
red = orginal.read().split()
for number in red:
if number % 2 == 0:
even.write(number + " ")
Input file:
15 12 6
7 20 9 10
13 17
3
You need to split each input line into tokens (assumed to represent integers) convert to int then determine if any value is even.
Something like this:
def write_positives(infile, outfile, mode='a'):
with open(infile) as fin, open(outfile, mode) as fout:
if (evens := [x for x in map(int, fin.read().split()) if x % 2 == 0]):
print(*evens, file=fout)
By printing the unpacked list you will, by default, have space separation
I have my input file as:
aa 12
bb 23
cc 34
dd 45
and so on... This is just the format of the file. My actual file has about 10,000s of lines. I want to get the output as :
\data\
n-grams = 4
\1-grams:
aa 12
bb 23
cc 34
dd 45
\end\
I have used this code:
with open("Input.txt") as infile:
with open("Output.txt","w") as outfile:
for i,line in enumerate(infile):
if i==0:
# 1st line
count = sum(1 for line in infile)
outfile.write("\data\ \n")
outfile.write("n-grams = " + str(count) + '\n\n')
outfile.write("\\1-grams:\n")
elif i==3:
# 4th line
pass
else:
outfile.write(line)
But, this code is inserting
\data\
n-grams = 3
\1-grams:
It is not printing the rest of the data. And, it is counting only 3 elements line instead of 4. How can I modify this to make it work?
I would do it this way:
with open('infile.txt', 'r') as f:
lines = f.readlines()
with open('outfile.txt', 'w') as f:
f.write('\\data\\\n')
f.write('n-grams = {}\n'.format(len(lines)))
f.write('\\1-grams:\n')
for l in lines:
f.write(l)
I know that Python can read numbers like:
8
5
4
2
2
6
But I am not sure how to make it read it like:
8 5 4 2 2 6
Also, is there a way to make python read both ways? For example:
8 5 4
2
6
I think reading with new lines would be:
info = open("info.txt", "r")
lines = info.readlines()
info.close()
How can I change the code so it would read downwards and to the sides like in my third example above?
I have a program like this:
info = open("1.txt", "r")
lines = info.readlines()
numbers = []
for l in lines:
num = int(l)
numbers.append(str(num**2))
info.close()
info = open("1.txt", "w")
for num in numbers:
info.write(num + "\n")
info.close()
How can I make the program read each number separately in new lines and in just lines?
Keeping them as strings:
with open("info.txt") as fobj:
numbers = fobj.read().split()
Or, converting them to integers:
with open("info.txt") as fobj:
numbers = [int(entry) for entry in fobj.read().split()]
This works with one number and several numbers per line.
This file content:
1
2
3 4 5
6
7
8 9 10
11
will result in this output for numbers:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
This approach reads the whole file at once. Unless your file is really large this is fine.
info = open("1.txt", "r")
lines = info.readlines()
numbers = []
for line in lines:
for num_str in line.split(' '):
num = int(num_str)
numbers.append(str(num**2))
info.close()
info = open("test.txt", "r")
lines = info.readlines()
numbers = []
for l in lines:
l = l.strip()
lSplit = l.split(' ')
if len(lSplit) == 1:
num = int(l)
numbers.append(str(num**2))
else:
for num in lSplit:
num2 = int(num)
numbers.append(str(num2**2))
print numbers
info.close()
A good way to do this is with a generator that iterates over the lines, and, for each line, yields each of the numbers on it. This works fine if there is only one number on the line (or none), too.
def numberfile(filename):
with open(filename) as input:
for line in input:
for number in line.split():
yield int(number)
Then you can just write, for example:
for n in numberfile("info.txt"):
print(n)
If you don't care how many numbers per line, then you could try this to create the list of the squares of all the numbers.
I have simplified your code a bit by simply iterating over the open file using a with statement, but iterating over the readlines() result will work just as well (for small files - for large ones, this method doesn't require you to hold the whole content of the file in memory).
numbers = []
with open("1.txt", 'r') as f:
for line in f:
nums = line.split()
for n in nums:
numbers.append(str(int(n)**2))
Just another not yet posted way...
numbers = []
with open('info.txt') as f:
for line in f:
numbers.extend(map(int, line.split()))
file_ = """
1 2 3 4 5 6 7 8
9 10
11
12 13 14
"""
for number in file_ .split():
print number
>>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
How to create new columns when writing to a CSV file? For example, I have a list of data:
Mylist = [1,3,67,43,23,52,7,9,21]
I would like to start a new line after every third value, so the output would look as follows, with each number in a separate cell and arranged into three columns (a 3x3 grid):
1 3 67\n
43 23 52\n
7 9 21\n
I know that the escape function \n is used to start a new line, but how would I go about starting a new column? I would prefer to use only BASIC Python read/write functions, not the imported csv module. This seems like it would be a fairly easy thing to do, but I can't figure it out.
Don't reinvent the wheel. You split up your list into evenly sized chunks, then use the csv module to produce your output:
import csv
with open(filename, 'wb') as outfile:
writer = csv.writer(outfile, delimiter=' ')
for i in xrange(0, len(Mylist), 3):
writer.writerow(Mylist[i:i + 3])
Even without the module, you can trivially join your columns using str.join(), but you have to explicitly map all values to strings first:
with open(filename, 'w') as outfile:
for i in xrange(0, len(Mylist), 3):
outfile.write(' '.join(map(str, Mylist[i:i + 3])) + '\n')
If you need to specifically pad your numbers to fit in columns 2 characters wide, add a format() call in a list comprehension:
with open(filename, 'w') as outfile:
for i in xrange(0, len(Mylist), 3):
outfile.write(' '.join([format(d, '<2d') for d in Mylist[i:i + 3]]) + '\n')
The '<2' width specifier left-aligns your numbers with whitespace.
Demo of the first and last options:
>>> import csv
>>> from io import BytesIO
>>> Mylist = [1,3,67,43,23,52,7,9,21]
>>> demo = BytesIO()
>>> writer = csv.writer(demo, delimiter=' ')
>>> for i in xrange(0, len(Mylist), 3):
... writer.writerow(Mylist[i:i + 3])
...
8L
10L
8L
>>> print demo.getvalue()
1 3 67
43 23 52
7 9 21
>>> demo = BytesIO()
>>> for i in xrange(0, len(Mylist), 3):
... demo.write(' '.join([format(d, '<2d') for d in Mylist[i:i + 3]]) + '\n')
...
9L
9L
9L
>>> print demo.getvalue()
1 3 67
43 23 52
7 9 21
try like this:
Mylist = [1,3,67,43,23,52,7,9,21]
with open('outfile', 'w') as f
for i in range(len(Mylist)):
if (i+1)%3 == 0:
f.write(" ".join(map(str, Mylist[i-2:i+1])) + '\n')
output:
1 3 67
43 23 52
7 9 21
Here's another option, maybe the easiest
#!/usr/bin/env python3
Mylist = [1,3,67,43,23,52,7,9,21]
filename = 'outfile.csv'
with open(filename, 'w') as outfile:
for i in range(0, len(Mylist), 3):
print('{} {} {}'.format(Mylist[i], Mylist[i+1], Mylist[i+2]))
Output
1 3 67
43 23 52
7 9 21
I have to take the values from a text file which contains the co-ordinates to draw characters out in TurtleWorld, an example of the text file is the following:
<character=B, width=21, code=66>
4 21
4 0
-1 -1
4 21
13 21
16 20
17 19
18 17
18 15
17 13
16 12
13 11
-1 -1
4 11
13 11
16 10
17 9
18 7
18 4
17 2
16 1
13 0
4 0
</character>
I have to then write a function to take all of these points and then convert them into a dictionary where a key is the character and the corresponding values are the set of points which can be used to draw that character in TurtleWorld.
The code I have tried is the following:
def read_font():
"""
Read the text from font.txt and convert the lines into instructions for how to plot specific characters
"""
filename = raw_input("\n\nInsert a file path to read the text of that file (or press any letter to use the default font.txt): ")
if len(filename) == 1:
filename = 'E:\words.txt'
words = open(filename, 'r')
else:
words = open(filename, 'r')
while True: # Restarts the function if the file path is invalid
line = words.readline()
line = line.strip()
if line[0] == '#' or line[0] == ' ': # Used to omit the any unwanted lines of text
continue
elif line[0] == '<' and line[1] == '/': # Conditional used for the end of each character
font_dictionary[character] = numbers_list
elif line[0] == '<' and line[1] != '/':
take a look at http://oreilly.com/catalog/pythonxml/chapter/ch01.html :: specifically, hit up the example titled :: Example 1-1: bookhandler.py
you can more or less credit/copy that and tweak it to read your particular xml. once you get the 'guts'(your coords), you can split it into a list of x/y coords really easily
such as
a = "1 3\n23 4\n3 9\n"
coords = map(int,a.split())
and chunk it into a list w/ groups of 2 How do you split a list into evenly sized chunks?
and store the result letters[letter] = result
or you can do the chunking more funky using the re module
import re
a = "1 13\n4 5\n"
b = re.findall("\d+ *\d+",a)
c = [map(int,item.split()) for item in b]
c
[[1, 13], [4, 5]]