I have to read each line in a file with indent.
Here's what I have, but it's not working...
f = open("filename.txt", "r")
print("\t" + f.read())
The indent only applies to the first line.
The .read() method returns the entire contents of a file. The method you want is .readlines(), which returns a list containing each line separately. The code you want looks more like this:
f = open("filename.txt")
lines = f.readlines()
for line in lines:
print("\t" + line)
Additionally, open() reads by default, so including 'r' isn't necessary. Enjoy coding!
Related
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 am trying to create a script that will take each line in my text file which includes one rule name in each of them. The first script I created worked (finished) but would delete everything in the file. I have been googling for past hour or so trying to take examples and apply them on my own but keep failing. The current script is as follows.
with open('TDAppendlist.txt', 'w') as file:
for line in file:
s = ('""')
seq = (file)
s.join(seq)
with open('TDAppendlist.txt') as file:
line = file.readlines()
for line in file:
line.join('"' + line + '"')
Neither of them are working. Could someone please point me in the correct direction? Thank you all for reading.
First, we'll read all the lines of the file into a list, then we can change them, and finally write them back to the file.
with open('TDAppendlist.txt') as file:
lines = list(file)
with open('TDAppendlist.txt', 'w') as file:
file.write('\n'.join(['"{}"'.format(line.rstrip('\n')) for line in lines]))
That last line can be written out to be more clear
lines = (line.rstrip('\n') for line in lines)
lines = ('"{}"'.format(line) for line in lines)
lines = '\n'.join(lines)
file.write(lines)
This produces an output file TDAppendlist_out that is just like the input, but with quotes surrounding the lines:
with open('TDAppendlist.txt', 'r') as f:
with open('TDAppendlist_out.txt', 'w') as f_out:
for line in f:
f_out.write('\"{}\"'.format(line))
This keeps the input file intact as is should you need it later, and avoids putting everything in the input file into memory all at once.
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.
import os.path
os.path.exists('~/fileToExperiment.txt')
myfile = open('~/fileToExperiment.txt','r')
myfile.readlines()
for line in myfile:
print line
So I am trying to run this very simple python code but it doesnot output anything nor does it has any errors.
The filestoExperiment text is not empty.
Whats wrong here ? Could someone point out
By doing, myfile.readlines() you already read the entire file. Then, we you try to iterate over your file object, you already are at the end of the file.
A better practice is to do:
with open('~/fileToExperiment.txt','r') as myfile:
for line in myfile:
print line
myfile.readlines() will store the whole content of the file in memory. If you do not need the entire content at once, it is best to read line by line.
If you do need the entire content, you can use
with open('~/fileToExperiment.txt','r') as myfile:
content = myfile.read() ## or content = myfile.readlines()
Also note the use of the with statement, which is recommended when handling files (no need to close the file afterwards).
You didn't store the lines in a variable. So try this:
lines = myfile.readlines()
for line in lines:
print line
You can use either readlines() or looping file object to print or read the lines from file.
readlines() - returns the complete file as a "list of strings each separated by \n"
for example,
code:
print myfile.readlines()
output:
['Hello World\n', 'Welcome to Python\n', 'End of line\n']
Looping file object - You can loop over the file object for reading lines from a file. This is memory efficient, fast, and leads to simple code. For example,
code:
myfile = open('newfile.txt', 'r')
for line in myfile:
print line
output:
Hello World
Welcome to Python
End of line
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))