How do I append text to a file with python? - python

I am trying to make a file that I can continuously add '../' to. My code is as follows:
with open("/tmp/newfile.txt", "a+") as myfile:
myfile.write('../')
contents = myfile.read()
print(contents)
However, when I run this code it returns <empty>

For Append File:
with open("newfile.txt", "a+") as file:
file.write("I am adding in more lines\n")
file.write("And moreā€¦")
For Read File:
with open('newfile.txt') as f:
lines = f.readlines()
print(lines)

Related

Write() starts halfway through

I am new to python and I really don't understand why this is happening: when I run my code, the lower() is only applied to half (or less) of the text file. How I can fix this?
import glob, os, string, re
list_of_files = glob.glob("/Users/louis/Downloads/assignment/data2/**/*.txt")
for file_name in list_of_files:
f = open(file_name, 'r+')
for line in f:
line = line.lower()
f.write(line)
The problem is most probably because you are reading and writing at the same time. And you need to return to the start of the file to write in place of the original content. Try this:
for file_name in list_of_files:
with open(file_name, 'r+') as f:
content = f.read().lower()
f.seek(0, 0) # returns to the start of the file
f.write(content)

on opening a data file to reading the lines included in that file

I am using the following code segment to partition a data file into two parts:
def shuffle_split(infilename, outfilename1, outfilename2):
with open(infilename, 'r') as f:
lines = f.readlines()
lines[-1] = lines[-1].rstrip('\n') + '\n'
shuffle(lines)
with open(outfilename1, 'w') as f:
f.writelines(lines[:90000])
with open(outfilename2, 'w') as f:
f.writelines(lines[90000:])
outfilename1.close()
outfilename2.close()
shuffle_split(data_file, training_file,validation_file)
Running this code segment cause the following error,
in shuffle_split
with open(infilename, 'r') as f:
TypeError: coercing to Unicode: need string or buffer, file found
What's wrong with the way of opening the data_file for input?
Whatever you're passing in as infilename is already a file, rather than a file's path name.

Read txt files, results in empty lines

I have some problem to open and read a txt-file in Python. The txt file contains text (cat text.txt works fine in Terminal). But in Python I only get 5 empty lines.
print open('text.txt').read()
Do you know why?
I solved it. Was a utf-16 file.
print open('text.txt').read().decode('utf-16-le')
if this prints the lines in your file then perhaps the file your program is selecting is empty? I don't know, but try this:
import tkinter as tk
from tkinter import filedialog
import os
def fileopen():
GUI=tk.Tk()
filepath=filedialog.askopenfilename(parent=GUI,title='Select file to print lines.')
(GUI).destroy()
return (filepath)
filepath = fileopen()
filepath = os.path.normpath(filepath)
with open (filepath, 'r') as fh:
print (fh.read())
or alternatively, using this method of printing lines:
fh = open(filepath, 'r')
for line in fh:
line=line.rstrip('\n')
print (line)
fh.close()
or if you want the lines loaded into a list of strings:
lines = []
fh = open(filepath, 'r')
for line in fh:
line=line.rstrip('\n')
lines.append(line)
fh.close()
for line in lines:
print (line)
When you open file I think you have to specify how do you want to open it. In your example you should open it for reading like:
print open('text.txt',"r").read()
Hope this does the trick.

How can i save this into a variable so that i can save it to a file

I have a bit of code which prints what I want to save but I cant save it as a variable because of the format. Please can you show me how to save this as a variable so that I can save it into a file
It wont let me add a picture but this is what I want to add to a variable (What its printing)
print(text[i],end="")
x = text[i]
with open("output.txt", 'w') as f:
f.write(x)
or
with open("output.txt", 'w') as f:
f.write(text[i])
Open a file:
f = open('filename','w')
Write a line of text to the file:
f.write(text[i])
And finally close the file:
f.close()

How can I tell python to edit another python file?

Right now, I have file.py and it prints the word "Hello" into text.txt.
f = open("text.txt")
f.write("Hello")
f.close()
I want to do the same thing, but I want to print the word "Hello" into a Python file. Say I wanted to do something like this:
f = open("list.py")
f.write("a = 1")
f.close
When I opened the file list.py, would it have a variable a with a value 1? How would I go about doing this?
If you want to append a new line to the end of a file
with open("file.py", "a") as f:
f.write("\na = 1")
If you want to write a line to the beginning of a file try creating a new one
with open("file.py") as f:
lines = f.readlines()
with open("file.py", "w") as f:
lines.insert(0, "a = 1")
f.write("\n".join(lines))
with open("list.py","a") as f:
f.write("a=1")
This is simple as you see. You have to open that file in write and read mode (a). Also with open() method is safier and more clear.
Example:
with open("list.py","a") as f:
f.write("a=1")
f.write("\nprint(a+1)")
list.py
a=1
print(a+1)
Output from list.py:
>>>
2
>>>
As you see, there is a variable in list.py called a equal to 1.
I would recommend you specify opening mode, when you are opening a file for reading, writing, etc. For example:
for reading:
with open('afile.txt', 'r') as f: # 'r' is a reading mode
text = f.read()
for writing:
with open('afile.txt', 'w') as f: # 'w' is a writing mode
f.write("Some text")
If you are opening a file with 'w' (writing) mode, old file content will be removed. To avoid that appending mode exists:
with open('afile.txt', 'a') as f: # 'a' as an appending mode
f.write("additional text")
For more information, please, read documentation.

Categories

Resources