I have a file and I would like to read the first line and write from the second.
with open(file_path, 'r+') as f:
f.readline()
for values in my_array:
f.write("%s=%s" % (str(values[0]), str(values[1])))
Any suggestion?
You can't write on a file while reading it.
Two solutions :
Have a second file where you rewrite your first line and then write the second one :
with open(file_path, 'r+') as f:
line = f.readline()
with open('another_file.txt', 'w') as outfile:
outfile.write(line)
outfile.write(...) # Whatever you want on your second line
Store everything you want to write in memory and then write over your previous file (Which I don't recommend, if something happens midway and your file is stil overwritten, all previous data will be lost).
Related
I have a txt file with 5 lines. I want to delete the first line copied after typing the text in the first line on the last line.
Example:
1
2
3
4
5
After:
2
3
4
5
1
my attempt
with open("equasisemail.txt", 'r') as file:
data = file.read().splitlines(True)
with open ("equasisemail.txt",'w') as fi:
fi.writelines(data[1:])
i use this to delete the first line.
read the lines using readlines (don't splitlines else you lose line terminator). Then write back the file using writelines then write the final line with a simple write
with open("equasisemail.txt", 'r') as file:
data = file.readlines()
# make sure the last line ends with newline (may not be the case)
if not data[-1].endswith("\n"):
data[-1] += "\n"
with open ("equasisemail.txt",'w') as fi:
fi.writelines(data[1:])
fi.write(data[0])
careful as if something bad happens during the write the file is destroyed. Better use another name, then rename once writing has completed. In which case what can be done is reading & writing at almost the same time on 2 separate filenames:
with open("equasisemail.txt", 'r') as fr,open ("equasisemail2.txt",'w') as fw:
first_line = next(fr) # manual iterate to get first line
for line in fr:
fw.write(line)
if not line.endswith("\n"):
fw.write("\n")
fw.write(first_line)
os.remove("equasisemail.txt")
os.rename("equasisemail2.txt","equasisemail.txt")
safer & saves memory. Fails if the file is empty. Test it first.
note: both solutions support files that don't end with a newline character.
To edit a file without creating a new file you can save the contents of the file to main memory, then open it in write mode:
input = open("email.txt", "r")
lines = input.readlines()
input.close()
output = open("email.txt", "w")
for i in range(1, len(lines)):
output.write(lines[i].strip() + "\n")
output.write(lines[0])
So I have a file with some lines of text:
here's a sentence
look! another one
here's a third one too
and another one
one more
and I have some code that takes the each line and puts it into a list and then reverses the order of the whole list but now I don't know how to write each line back to the file and delete the existing ones in the text file.
Also when I run this code:
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
everything works and the line order is reversed, but when I run this code:
text_file = open(file_name, "w")
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
for line in file_lines:
text_file.write(line)
it prints empty lists for some reason.
You can fix it by doing just 2 little changes in your script.
Use \r+ in place of \w+
Before performing write operation, place file position indicator to the beginning
text_file.seek(0)
» rw_file.txt - before operation
here's a sentence
look! another one
here's a third one too
and another one
one more
Below is your modified script to reverse the content of file (It worked).
def reverseFile(file_name):
text_file = open(file_name, "r+") # Do not use 'w+', it will erase your file content
file_lines = [line.rstrip('\n') for line in text_file.readlines()]
file_lines.reverse()
print(file_lines)
text_file.seek(0) # Place file position indicator at beginning
for line_item in file_lines:
text_file.write(line_item+"\n")
reverseFile("rw_file.txt")
» rw_file.txt - after operation
one more
and another one
here's a third one too
look! another one
here's a sentence
If you open the file in 'w' mode, the file is erased. From the docs:
'w' for only writing (an existing file with the same name will be
erased)
You should also use the with keyword:
It is good practice to use the with keyword when dealing with file
objects. The advantage is that the file is properly closed after its
suite finishes...
I would recommend you read the contents of the file first, process that data, and then write:
def reverseFile(file_name):
with open(file_name, 'r') as f:
file_lines = [line.rstrip('\n') for line in f.readlines()]
file_lines.reverse()
with open(file_name, "w") as f:
for line in file_lines:
f.write(line + '\n')
reverseFile('text_lines.txt')
I wrote the following python code snippet to append a lower p character to each line of a txt file:
f = open('helloworld.txt','r')
for line in f:
line+='p'
print(f.read())
f.close()
However, when I execute this python program, it returns nothing but an empty blank:
zhiwei#zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
Can anyone tell me what's wrong with my codes?
Currently, you are only reading each line and not writing to the file. reopen the file in write mode and write your full string to it, like so:
newf=""
with open('helloworld.txt','r') as f:
for line in f:
newf+=line.strip()+"p\n"
f.close()
with open('helloworld.txt','w') as f:
f.write(newf)
f.close()
well, type help(f) in shell, you can get "Character and line based layer over a BufferedIOBase object, buffer."
it's meaning:if you reading first buffer,you can get content, but again. it's empty。
so like this:
with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
newline = ''
for line in f1:
newline+=line.strip()+"p\n"
f2.write(newline)
open(filePath, openMode) takes two arguments, the first one is the path to your file, the second one is the mode it will be opened it. When you use 'r' as second argument, you are actually telling Python to open it as an only reading file.
If you want to write on it, you need to open it in writing mode, using 'w' as second argument. You can find more about how to read/write files in Python in its official documentation.
If you want to read and write at the same time, you have to open the file in both reading and writing modes. You can do this simply by using 'r+' mode.
It seems that your for loop has already read the file to the end, so f.read() return empty string.
If you just need to print the lines in the file, you could move the print into for loop just like print(line). And it is better to move the f.read() before for loop:
f = open("filename", "r")
lines = f.readlines()
for line in lines:
line += "p"
print(line)
f.close()
If you need to modify the file, you need to create another file obj and open it in mode of "w", and use f.write(line) to write the modified lines into the new file.
Besides, it is more better to use with clause in python instead of open(), it is more pythonic.
with open("filename", "r") as f:
lines = f.readlines()
for line in lines:
line += "p"
print(line)
When using with clause, you have no need to close file, this is more simple.
I wrote a program that opens a file and read it line by line and store just the third element of each line. The problem is that, when I write those outputs into a file I need to change them as strings which is not suitable for me due to the fact that I want to do some mathematical operations on the written file later on. FYI, it also is not suitable to store it like this and use int() while reading it.
Can anybody help me with this issue?
with open("/home/test1_to_write", "w") as g:
with open("/home/test1_to_read", 'r') as f:
for line in f:
a=line.split()
number = int(a[3])
g.write(str(number)+'\n')
g.close()
There's no way to tell a text file that 1 is the number one not the letter "1". If you need that, consider storing the whole thing as a list instead using some sort of serial format e.g. JSON:
import json
with open("/home/test1_to_write.json", 'w') as outfile:
with open("/home/test1_to_read", 'r') as infile:
data = [int(line.split()[3]) for line in infile]
json.dump(data, outfile)
You can then load the data with:
with open("/home/test1_to_write.json", "r") as infile:
read_data = json.load(infile)
I am a newbie to python and trying to read file line by line and append a word at the end of each line. The "print line" shows that the required word has got appended but the same thing not written back to the file as required . Appreciate your help.
#!/usr/bin/python
f=open('test1', 'r+')
for line in f:
line=line.strip("\n")
line=line +" " + 'test2'
print line
f.write(line)
f.close()
Generally speaking, reading/writing a file at the same time is a really horribly difficult thing to get right. Usually, you'll read from one file and write to a different file (possibly in memory). An in-memory implementation would be something like:
with open('test1', 'r') as fin:
lines = [line.strip('\n') + ' test2\n' for line in fin]
with open('test1', 'w') as fout:
fout.writelines(lines)
Notice that I read all the file's data into memory in the first with block. In the second with block, I write all that data back out to a new file (which conveniently has the same name as the old file effectively overwriting the old). Of course, if memory is a problem, you can read a line and then write a line to a new file (with a different name). After you've closed and flushed both files, then you can use shutil.move to rename the new file so that you overwrite the old one.
#mgilson's answer is very well, and just a little error is the lines in the end of lines = [line.strip('\n') + ' test2\n' for line in lines] should be fin.
The code given by mgilson is great! However, the function you request is not possible if you read and append at the same time.
I am too new to python.
So, I find myself more comfort in the following syntax.
# read in
f = open('test1', 'r')
newlines = []
for line in f:
newline = line.strip("\n") + " " + 'test2' + "\n"
newlines.append(newline)
print newline,
f.close()
# overwrite the same file
f = open('test1', 'w')
f.writelines(newlines)
f.close()
mgilson's code is slightly wrong. Corrected:
with open("test1", "r") as f:
new_contents = [line.strip() + "test2" for line in f.readlines()]
with open("test1", "w") as f:
f.write("\n".join(new_contents))