Text Files, and New Lines - python

If I have this code to write a txt file I am just wondering why every time I type \n in the input it doesn't create a newline so like this.
This is the example txt file\n it doesn't create a new line\n how can I make it do it?
This is the code
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text)
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(["\n", text])
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()

You can use replace:
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(text.replace('\\n', '\n'))
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(text.replace('\\n', '\n'))
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()

Here's a very simplified answer.
input = input("Would you like to Write a new document, or Edit an existing one? ")
if input == Write:
file = open(path, "w")
file.write(text)
file.write("\r\n")
file.close()
if input == Edit:
file = open(path, "a")
file.write(text)
file.write("\r\n")
file.close()

The reason why \n doesn't work with input is mentioned in How do you input escape sequences in Python?. The input function doesn't recognize any escape sequences, such as \n, because it interprets the text literally.
To interpret \n as a new line from text, have these imports and adjust the arguments for write() and writelines() allowing a user to input, This is the example txt file\n it doesn't create a new line\n how can I make it do it? to include new lines:
import ast # Add imports
import shlex
def create():
path = input("What file would you like to create: ")
output_file = open(path, 'x')
text = input("What would you like to write? ")
output_file.write(ast.literal_eval(shlex.quote(text))) # Evaluate escape sequences
output_file.close()
def append():
path = input("What file would you like to append: ")
output_file = open(path, 'a')
text = input("What would you like to write?")
output_file.writelines(["\n", ast.literal_eval(shlex.quote(text))]) # Evaluate escape sequences
output_file.close()
write = input("Would you like to write something today, or edit? ")
if write == "Write":
create()
if write == "Edit":
append()

Related

Save input as text file in python

I got a simple python code with some inputs where a user has to type name, age, player name and his best game.
Now I want that all these inputs from the user were saved as a text file or something like this.
I tried
with open ("Test_", "a") as file:
User_input = file.write(input("here type in your name"))
I tried it with with open ... n where I create a new text file before which I open in python and add something. But everything I tried failed. Hope my English is good enough to understand what kind of problem I have.
import csv
OUTFILE = 'gameplayers.csv'
def main():
player = []
morePlayer = 'y'
while morePlayer == 'y':
name = input('Enter your name: ')
age = input('Your age: ')
playerName = input('Your player name: ')
bestGame = input('What is your best game: ')
player.append([name, age, playerName, bestGame])
morePlayer = input('Enter information of more players: (y, n): ')
with open(OUTFILE, 'a', encoding='utf_8') as f:
csvWriter = csv.writer(f, delimiter=',')
csvWriter.writerows(player)
if __name__ == '__main__':
main()
If you want to keep adding new data, use a otherwise, use w to overwrite. I've used a in this example:
name = input('Name: ')
age = input('Age: ')
best_game = input('Best Game: ')
with open('user_data.txt', 'a') as file:
file.write(f'Name: {name} - Age: {age} - Best Game: {best_game}\n')
First of all, you need to know the difference between 'a' and 'w' in with open. 'w' stands for write, meaning every time you call it, it will be overwritten. 'a' stands for append, meaning new information will be appended to the file. In your case, I would have written the code something like this
userInput = input(“Enter your name: “)
with open(“filename.txt”, “a”) as f:
f.write(userInput)
If you instead want to overwrite every time - change the 'a' to a 'w'.

How do i change this so when i run the functions it adds to my .txt file?

Im supposed to make a function for adding name and number to a.txt file, and one for reading the file. What am I doing wrong and how do I correct it? first post so I dont know if something is in the wrong format, sorry.
def add():
while True:
name = input("Name and number: ")
with open("Telefon.txt", "a") as f:
f.write(name)
f.close()
if name == "Enter":
break
def read():
f = open("Telefon.txt", "r")
print(f.read)
There are certain logical and optimizations mistake in your code you should not open file again and again and close it in loop, also use empty condition to terminate the loop e.g. press enter without entering any thing. For reading, I replaced your read method with redlines method
def add():
with open("Telefon.txt", "a") as f:
while True:
name = input("Name and number: ")
f.write(name + '\n')
if name == "":
break
def read():
f = open("Telefon.txt", "r")
print("".join(f.readlines()))
add()
read()
The output is following

How to pass a returned value into another function

I am trying to call the list I created in a sub-function, into another sub-function. Using parameters and call functions are my Achilles heel as it relates to python. I want to call the newList I created in the calculateZscore function, into mu globalChi function.
My current code:
import os
import math
'''
c:/Scripts/Lab2Data
NCSIDS_ObsExp.txt
chisquare.txt
output.txt
'''
def main():
directory = raw_input ("What is the working directory? ")
input_file = raw_input ("What is the name of the input file? ")
chiTable = raw_input ("What is the name of the chi-squared table? ")
outPut = raw_input ("What is the name of the output file? ")
path = os.path.join(directory,input_file)
path_1 = os.path.join(directory, chiTable)
path_2 = os.path.join(directory, outPut)
if __name__ == "__main__":
main()
def calculateZscore(inFileName, outFileName):
inputFile = open(inFileName,"r")
txtfile = open(outFileName, 'w')
for line in inputFile:
newList = line.strip().split(',')
obsExp = newList[-2:]
obsExp = list(map(int, obsExp))
obs = obsExp[0]
exp = obsExp[1]
zScore = (obs - exp) / math.sqrt(exp)
zScore = map(str, [zScore])
newList.extend(zScore)
txtfile = open(outFileName, 'w')
txtfile.writelines(newList)
inputFile.close() #close the files
txtfile.close()
return newList #return the list containing z scores
def globalChi(zscoreList):
print newList
You should read about the return statement. It is used to make a function return a result (the opposite of taking an argument), and cannot be used outside a function.
Here, you are doing the exact opposite.

Python says: "expected an indented block"

I've been playing around with Python a bit recently and have come across this error when creating functions. I can't seem to fix it :(. CODE:
Python
#Python
choice = input('Append Or Write?')
if choice == "write":
def write():
pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
if choice == "append":
def append():
# Making a txt file
#Append
pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
You forgot to call your functions that you defined. pass may also be causing the statements in your function to get ignored, remove pass.
Reformatting your code:
#Python
def append():
# Making a txt file
#Append
# pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()
def write():
# pass
text_file = open('WrittenTXT.txt', "w")
type_user = input('Type: ')
text_file.write(type_user)
text_file.close()
choice = input('Append Or Write?')
if choice == "write":
write()
if choice == "append":
append()

Trying to print only one line of a text document in python

I am making a program that lets you edit, or read a text document in python, and I'm not finished yet, and I'm stuck on the reading part. I want it to print only one line, and I'm drawing a blank on how to do so. The read part is in "def read():"
def menu():
print("What would you like to do?")
print("\n(1) Write new text")
print("(2) Read line 3")
choice = float(input())
if choice == 1:
write()
elif choice == 2:
read()
def read():
with open('test.txt', 'r') as read:
print()
def write():
print("\nType the full name of the file you wish to write in.")
file1 = input().strip()
with open(file1, "a") as add:
print("What do you want to write?")
text = input()
add.write("\n"+ text)
menu()
def read():
with open('test.txt', 'r') as f:
for line in f:
print(line)
Edit:
def read():
with open('test.txt', 'r') as f:
lines = f.readlines()
print lines[1]
You can use the file as an iterable, and loop over it, or you can call .next() on it to advance one line at a time.
If you need to read 1 specific line, this means you can skip the lines before it using .next() calls:
def read():
with open('test.txt', 'r') as f:
for _ in range(2):
f.next() # skip lines
print(f.next()) # print the 3rd line
I figured mine out pretty late since i do not use the 'def' function, but this prints out the line that you want to print
import os.path
bars = open('bars.txt', 'r')
first_line = bars.readlines()
length = len(first_line)
bars.close()
print(first_line[2])

Categories