Multiple lines in file appearing as only one line [duplicate] - python

This question already has answers here:
write() versus writelines() and concatenated strings
(5 answers)
Closed 3 years ago.
I am trying to save some variables to a file on separate lines.
My code looks like this:
def saveall(sname, senemyname, scheckpoint,):
file = open("savefile.sav", "w")
file.writelines([sname, senemyname, scheckpoint])
file.close()
If I put saveall("John","Steve","Crossroads") in my code, I want it to make a file called savefile.sav, containing:
John
Steve
Crossroads
However, when I run the program, savefile.sav contains:
JohnSteveCrossroads
What am I doing wrong?

writelines expects each string to be newline terminated. So you need:
file.writelines([sname + '\n', senemyname + '\n', scheckpoint + '\n'])
From the python docs:
writelines(lines)
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
But usually it's more idiomatic to do file.write('\n'.join([sname, senemyname, scheckpoint)). Note that that doesn't add the file newline.
You should also be using contexts for files, because if an exception is raised you may not close your file:
with open('savefile.sav', 'w') as f:
f.write('\n'.join([sname, senemyname, scheckpoint]))

writelines doesn't add separators between the lines, so you have to add them yourself:
def saveall(sname, senemyname, scheckpoint,):
file = open("savefile.sav", "w")
file.writelines((line + '\n' for line in [sname, senemyname, scheckpoint]))
file.close()
saveall("John","Steve","Crossroads")
File content:
John
Steve
Crossroads

Related

How to delete the last 4 characters from every line in a file? - Python [duplicate]

This question already has answers here:
Is it possible to modify lines in a file in-place?
(5 answers)
Closed 2 years ago.
Can anyone give me some advice on creating a loop to cut the last 4 characters from every line within an input file?
I have tried:
myfile = open('delete.txt', 'w+')
myfile.read()
for line in myfile:
line = line[:3]
myfile.close()
The file is formatted like thi:
Awks,1er,xyz,lon,thr,tkj,,^M
Atks,1er,xyz,lon,thr,toj,,^M
Ahks,1er,xyz,lon,thr,taj,,^M
Auks,1er,xaz,lon,thr,tej,,^M
Aqks,1er,xyz,lon,thr,twj,,,^M
Aoks,1er,xaz,lon,thr,twj,,^M
Apks,1er,xwz,lon,thr,trj,,^M
Alks,1er,xuz,lon,thr,toe,,^M
ssks,1er,xoz,lon,thr,toj,,^M
ssks,1er,xnz,lon,thr,tog,,,^M
As some comments said, it's probably safer to open up the input file and write output to a separate file.
Using a with block is handy, because you don't need to handle closing a file; your file is automatically closed at the end of the block.
I'd do something like this:
with open('input.txt', 'r') as infile:
with open('output.txt', 'w') as outfile:
for line in infile:
outfile.write(line[:-5])
outfile.write('\n')
The line[:-5] will remove the last five characters of each line, which is probably what you want since each line also contains a newline, so it removes the newline and four characters. We outfile.write('\n') because the newline was removed, and we want it back.

What is the difference between read() and readline() in python? [duplicate]

This question already has answers here:
When should I ever use file.read() or file.readlines()?
(5 answers)
Closed 3 years ago.
I am learning file handling in python right now. If i write read() method , it does work same as readline() method . There must be a difference between them and i want to learn that
This question has been answered countless times, and the documentation does a good job of describing the differences, too. But here goes:
If you have a file (test.txt) like so:
first line
second line
third line
Then this code:
with open("test.txt", "r") as file:
line = file.readline()
print(line)
Will produce this output:
first line
That's because readline just reads the next line.
If you use this code instead:
with open("test.txt", "r") as file:
content = file.read()
print(content)
Output:
first line
second line
third line
read() reads the entire contents of the file into a string.
You can also give read() an optional argument, which designates the number of characters to read from the file:
with open("test.txt", "r") as file:
content = file.read(15)
print(content)
Output:
first line
seco
Finally, the third function, which you didn't mention, is readlines, which returns a list of lines (strings):
with open("test.txt", "r") as file:
lines = file.readlines()
print(lines)
Output:
['first line\n', 'second line\n', 'third line\n']
The main difference is that read() will read the whole file at once and then print out the first characters that take up as many bytes as you specify in the parenthesis versus the readline() that will read and print out only the first characters that take up as many bytes as you specify in the parenthesis. You may want to use readline() when you're reading files that are too big for your RAM.

Replace line containing string with Python [duplicate]

This question already has answers here:
How to open a file for both reading and writing?
(4 answers)
Closed 6 years ago.
I'm trying to search through a file for a line that contain certain text and then replace that entire line with a new line.
I'm trying to use:
pattern = "Hello"
file = open('C:/rtemp/output.txt','w')
for line in file:
if pattern in line:
line = "Hi\n"
file.write(line)
I get an error saying:
io.UnsupportedOperation: not readable
I'm not sure what I'm doing wrong, please can someone assist.
You opened the file with 'w', meaning you are going to write to it. Then you try to read from it. So error.
Try reading from that file, and open another file for writing your output. If needed, when done, delete the first file and rename your output (temp) file to the first file's name.
You must be very new for python ^_^
You can write it like this:
pattern = "Hello"
file = open(r'C:\rtemp\output.txt','r') # open file handle for read
# use r'', you don't need to replace '\' with '/'
# open file handle for write, should give a different file name from previous one
result = open(r'C:\rtemp\output2.txt', 'w')
for line in file:
line = line.strip('\r\n') # it's always a good behave to strip what you read from files
if pattern in line:
line = "Hi" # if match, replace line
result.write(line + '\n') # write every line
file.close() # don't forget to close file handle
result.close()

How to remove line from the file in python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Deleting a specific line in a file (python)
I need to delete the line contains number '2' from the file f=
2 3
5 6
7 2
4 5
When you want to edit a file, you make a new file with the correct data and then rename the new file as the old file. This is what serious programs like your text editor probably do. (Some text editors actually do even weirder stuff, but there's no use going into that.) This is because in many filesystems the rename can be atomic, so that under no circumstances will you end up with the original file being corrupted.
This would lead to code to the effect of
with open(orig_file) as f, open(working_file, "w") as working:
# ^^^ 2.7+ form, 2.5+ use contextlib.nested
for line in f:
if '2' not in line: # Is this exactly the criterion you want?
# What if a line was "12 5"?
working.write(line)
os.rename(working_file, orig_file)
You may want to use orig_file + '~' or the tempfile module for generating the working file.
with open('f', 'r+') as f:
data = ''.join(filter(lambda l: '2' not in l.strip().split(' '), f))
f.seek(0)
f.truncate(0)
f.write(data)
import fileinput
for line in fileinput.input('f',inplace =1):
line = line.strip()
if not '2' in line:
print line

Replace string within file contents [duplicate]

This question already has answers here:
Replacing instances of a character in a string
(17 answers)
How to search and replace text in a file?
(22 answers)
How to read a large file - line by line?
(11 answers)
Writing a list to a file with Python, with newlines
(26 answers)
Closed 7 months ago.
How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:
I am using the with statement in this example, which closes the file after the with block is terminated - either normally when the last command finishes executing, or by an exception.
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.
#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName, "w") as f:
f.write(newText)
Using pathlib (https://docs.python.org/3/library/pathlib.html)
from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))
If input and output files were different you would use two different variables for read_text and write_text.
If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.
If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.
Something like
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
with open('Stud.txt','r') as f:
newlines = []
for line in f.readlines():
newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
for line in newlines:
f.write(line)
If you are on linux and just want to replace the word dog with catyou can do:
text.txt:
Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Linux Command:
sed -i 's/dog/cat/g' test.txt
Output:
Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...
import re
input = file('C:\full_path\Stud.txt', 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first.
saved_input
for eachLine in input:
saved_input.append(eachLine)
#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
search = re.sub('A', 'Orange', saved_input[i])
if search is not None:
saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt', 'w')
for each in saved_input:
input.write(each)

Categories