Insert new data for each text line in python - python

I have a text file that looks like this:
1,004,59
1,004,65
1,004,69
1,005,55
1,005,57
1,006,53
1,006,59
1,007,65
1,007,69
1,007,55
1,007,57
1,008,53
Want to create new text file that will be inserted by 'input', something like this
1,004,59,input
1,004,65,input
1,004,69,input
1,005,55,input
1,005,57,input
1,006,53,input
1,006,59,input
1,007,65,input
1,007,69,input
1,007,55,input
1,007,57,input
1,008,53,input
I have attempted something like this:
with open('data.txt', 'a') as f:
lines = f.readlines()
for i, line in enumerate(lines):
line[i] = line[i].strip() + 'input'
for line in lines:
f.writelines(line)
Not able to get the right approach though.

What you want is to be able to read and write to the file in place (at the same time). Python comes with the fileinput module which is good for this purpose:
import fileinput
for line in fileinput.input('data.txt', inplace=True):
line = line.rstrip()
print line + ",input"
Discusssion
The fileinput.input() function returns a generator that reads your file line by line. Each line ends up with a new line (either \n or \r\n, depends on the operating system).
The code then strip off each line of this new line, add the ",input" part, then print out. Note that because of fileinput magic, the print statement's output will go back into the file instead of the console.

There are a newline '\n' in every line in your file, so you should handle it.
edit: oh I forgot about the rstrip() function!
tmp = []
with open("input.txt", 'r') as file:
appendtext = ",input\n"
for line in file:
tmp.append(line.rstrip() + appendtext)
with open("input.txt", 'w') as file:
file.writelines(tmp)
Added:
Answer by Hai_Vu is great if you use fileinput since you don't have to open the file twice as I did.

To do only the thing you're asking I would go for something like
newLines = list()
with open('data.txt', 'r') as f:
lines = f.readlines()
for line in lines:
newLines.append(line.strip() + ',input\n')
with open('data2.txt', 'w') as f2:
f2.writelines(newLines)
But there are definitely more elegant solutions

Related

Meditation with texts in a text file in the case of threading

iam using this code to to pull the first line at text file at threading mod before delete it from the file
with open(r'C:\datanames\names.txt','r') as fin:
name = fin.readline()
with open(r'C:\datanames\names.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open(r'C:\datanames\names.txt', 'w') as fout:
fout.writelines(data[1:])
put it make me lose the data Often
Is there a more efficient and practical way to use it in such a situation? (threading)
I see no reason to use threading for this. It's very straightforward.
To remove the first line from a file do this:
FILENAME = 'foo.txt'
with open(FILENAME, 'r+') as file:
lines = file.readlines()
file.seek(0)
file.writelines(lines[1:])
file.truncate()

Is there way to close a file in python, without a file object?

I can't close this file, as the file is directly fed into the 'lines'-list.
I have tried closing with command lines.close() but it doesn't work.
def readfile():
lines = [line.rstrip('\n') for line in open('8ballresponses.txt', 'r')]
print(random.choice(lines))
I don't get an error, but i want to be able to close the file.
Instead of file object, lines is a list , so you can't close it. And you should store file object open('8ballresponses.txt', 'r') with a variable for closing it later:
def readfile(file_path):
test_file = open(file_path, 'r')
lines = [line.rstrip('\n') for line in test_file]
test_file.close()
print(random.choice(lines))
Or simply use with "to close a file in python, without a file object":
def readfile(file_path):
with open(file_path, 'r') as test_file:
lines = [line.rstrip('\n') for line in test_file]
print(lines)
you can use with open command. this will automatically handle all the test cases failure etc. (inbuild try except and finally in python)
below is example similiar to your code
import random
def readfile():
lines = []
with open(r"C:\Users\user\Desktop\test\read.txt",'r') as f:
lines = f.readlines()
print(random.choice(lines))
You can use try and finally block to do the work.
For example :
def readfile():
file = open('8ballresponses.txt', 'r')
try:
lines = [line.rstrip('\n') for line in file]
print(random.choice(lines))
finally:
file.close()
In this post
"When the with ends, the file will be closed. This is true even if an exception is raised inside of it."
You manually invoke the close() method of a file object explicitly or implicitly by leaving a with open(...): block. This works of course always and on any Python implementation.
Use with this will close implicitly after the block is complete
with open('8ballresponses.txt', 'r') as file:
lines = [ line.rstrip("\n") for line in file ]

Text file opening in python

Could someone give me some guidance on how you would get the contents of your text file on my python code without opening up the text file in another window?
Just point me in the right direction on how I should do it (No need for solutions)
with open(workfile, 'r') as f:
for line in f:
print line
If you don't use the context manager (the with statement) you will need to explicitly call f.close(), for example:
f = open('workfile', 'r')
line = f.readline()
print line
f.close()
file = open("your_file.txt", "r")
file.read()

Appends text file instead of overwritting it

The context is the following one, I have two text file that I need to edit.
I open the first text file read it line by line and edit it but sometimes when I encounter a specific line in the first text file I need to overwritte content of the the second file.
However, each time I re-open the second text file instead of overwritting its content the below code appends it to the file...
Thanks in advance.
def edit_custom_class(custom_class_path, my_message):
with open(custom_class_path, "r+") as file:
file.seek(0)
for line in file:
if(some_condition):
file.write(mu_message)
def process_file(file_path):
with open(file_path, "r+") as file:
for line in file:
if(some_condition):
edit_custom_class(custom_class_path, my_message)
In my opinion, simultaneously reading and modifying a file is a bad thing to do. Consider using something like this. First read the file, make modifications, and then overwrite the file completely.
def modify(path):
out = []
f = open(path)
for line in f:
if some_condition:
out.append(edited_line) #make sure it has a \n at the end
else:
out.append(original_line)
f.close()
with open(path,'w') as f:
for line in out:
f.write(line)

Search text file and save result to another text file

I am pretty new to python and have only very limited programming skills with it. I hope you can help me here.
I have a large text file and I'm searching it for a specific word. Every line with this word needs to be stored to another txt file.
I can search the file and print the result in the console but not to a different file. How can I manage that?
f = open("/tmp/LostShots/LostShots.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "Lost" in line:
for l in searchlines[i:i+3]: print l,
print
f.close()
Thx
Jan
Use with context manager, do not use readlines() since it will read the whole contents of a file into a list. Instead iterate over file object line by line and see if a specific word is there; if yes - write to the output file:
with open("/tmp/LostShots/LostShots.txt", "r") as input_file, \
open('results.txt', 'w') as output_file:
for line in input_file:
if "Lost" in line:
output_file.write(line)
Note that for python < 2.7, you cannot have multiple items in with:
with open("/tmp/LostShots/LostShots.txt", "r") as input_file:
with open('results.txt', 'w') as output_file:
for line in input_file:
if "Lost" in line:
output_file.write(line)
To correctly match words in general, you need regular expressions; a simple word in line check also matches blablaLostblabla which I assume you don't want:
import re
with open("/tmp/LostShots/LostShots.txt", "r") as input_file, \
open('results.txt', 'w') as output_file:
output_file.writelines(line for line in input_file
if re.match(r'.*\bLost\b', line)
or you can use a more wordy
for line in input_file:
if re.match(r'.*\bLost\b', line)):
output_file.write(line)
As a side note, you should be using os.path.join to make paths; also, for working with temporary files in a cross-platform manner, see the functions in the tempfile module.

Categories