Feb-27-2018, 02:19 PM
Hello everyone,
I am about to take a random sample (n = 2) from a tab-separated "ran.txt"-file displayed right below, but I only want to print the first and second column to a new output-file "out.txt".
So far, I have managed to take the sample with the code you can see below. I have used linesstr = ''.join(rl) to join lines to a printable string, which surely is part of my problem.
So my question is: what would be the right code to print line[0] and line[1] to a new file? I was thinking about a loop, but a I don't know how to combine it with the random.sample(input.readlines(). Any ideas?
input-file "ran.txt":
I am about to take a random sample (n = 2) from a tab-separated "ran.txt"-file displayed right below, but I only want to print the first and second column to a new output-file "out.txt".
So far, I have managed to take the sample with the code you can see below. I have used linesstr = ''.join(rl) to join lines to a printable string, which surely is part of my problem.
So my question is: what would be the right code to print line[0] and line[1] to a new file? I was thinking about a loop, but a I don't know how to combine it with the random.sample(input.readlines(). Any ideas?
input-file "ran.txt":
Output:45378 BNA 125 CALEC
74231 BNA 125 CALEC
469 FSE 176 CALEC
2347893 FSE 176 CALEX
4273897 KLW 089 CALEX
output in "out.txt" should be for example:Output:74231 BNA
4273897 KLW
Here is the code and output I achieved the n=2 sample with:import os import io import random os.chdir("...") input = io.open("ran.txt","r", encoding="utf-8") rl = random.sample(input.readlines(),2) out = open("out.txt", "w", encoding="utf-8") linesstr = ''.join(rl) print(linesstr, file=out) input.close() output.close()
Output:74231 BNA 125 CALEC
469 FSE 176 CALEC
I tried to replace the code for writing into the output-file by the following, but it will only give me one random line, not the first column. Obviously, readlines() has to be done in another way...out = open("out.txt", "w", encoding = "utf-8") print(rl[0], file=out)Thanks for your help!