This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 3 years ago.
I want to change my code from read and process from a string of sentence into read from a csv file, and process line by line.
This is my program in VS Code.
import paralleldots
paralleldots.set_api_key("API KEY")
# for single sentence
text="Come on, lets play together"
lang_code="en"
response=paralleldots.sentiment(text,lang_code)
print(response)
I expect the output is run for each line of sentence in a specific csv file, instead of just from a string of sentence.
fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
lines = fp.read().split("\n") # Create a list containing all lines
fp.close() # Close file
print(lines)
#print("----------------------------------------------...------\n")
print("\nThe emotion analysis results for each sentence in the file .txt :")
print("------------------------------------------------...------\n")
response=paralleldots.batch_emotion(lines)
print(response)
This worked well.
Related
This question already has answers here:
Search for a word in file & print the matching line - Python
(2 answers)
search value for key in file using python
(2 answers)
Parse key value pairs in a text file
(7 answers)
Closed 2 months ago.
I have a text file with data
Theme="dark_background"
Color="Blue"
Now from the text file I just want to read the value of a Theme in python i.e dark_background
with open("nxc.txt","r") as f:
asz = f.read()
Above is the code for reading whole text file
Don't call .read() (which slurps the whole file when you only need one line), just loop over the file object itself (which is an iterator of its lines) until you find the line you care about:
with open("nxc.txt") as f:
for line in f:
name, sep, value = line.rstrip().partition('=') # Remove trailing whitespace, split on = at most once
if sep and name == 'Theme': # Cheap to confirm it split by check if sep non-empty, then check if found correct name
break # You found it, break out of the loop
# value contains whatever is to the right of the equals after Theme
print(value)
Something like this,
Theme=""
Color=""
with open('c:\\config.file') as f:
for line in f:
if line.startswith("Theme"):
Theme = line.split("=")[1].strip()
if line.startswith("Color"):
Color = line.split("=")[1].strip()
If you just want to read the first line of a file, you can use readline()
eg.
with open("nxc.txt","r") as f:
asz = f.readline()
If you want to read a particular value, you have no choice but to load the whole file and parse it in Python. This is because Python has no idea about the overall structure of the file.
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
How do i print each line in a .txt file one by one in a while loop in python
(1 answer)
Closed 3 months ago.
I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn't work.
with open("Scores.txt", "r") as scores:
for i in range(len(score.readlines())):
print(score.readlines(i + 1))
Instead of printing each line of the .txt file as I expected it to instead it just prints []
The contents of the .txt file are:
NAME: AGE: GENDER: SCORE:
I know it's only one line but it should still work shouldn't it?
*Note there are spaces between each word in the .txt file, though Stack Overflow formatting doesn't allow me to show that.
Assign the result of score.readlines() to a variable. Then you can loop through it and index it.
with open("Scores.txt", "r") as scores:
scorelines = scores.readlines()
for line in scorelines:
print(line)
.readlines() reads everything until it reaches the end of the file. Calling it repeatedly will return [] as the file seeker is already at the end.
Try iterating over the file like so:
with open("Scores.txt", "r") as scores:
for line in scores:
print(line.rstrip())
This question already has answers here:
Prepend line to beginning of a file
(11 answers)
Closed 1 year ago.
I have build a code that does the following:
#code is supposed to access servers about 20 of them
#server details are in 'CheckFolders.ini'
# retrieve size, file numbers and number of folders information
# put all that in a file CheckFoldersResult.txt
Need to find out how can i write to CheckFoldersResult.txt so that the latest results are appended starting from the beginning of the file instead of appending at end of the existing text.
I'd read the results, insert the lines I want at the top, then overwrite the file like so:
def update_file(filepath, new_lines):
lines = []
with open(filepath, 'r') as f:
lines = f.readlines()
rev_lines = reversed(new_lines)
for line in rev_lines:
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
This question already has answers here:
How to search and replace text in a file?
(22 answers)
Closed 2 years ago.
with open("textfile.txt", 'r+') as fin:
text = fin.read()
fin.write(text.replace(" full stop ","."))
fin.write(text.replace("New Paragraph","\n \t"))
I want to add punctuation in the file. e.g. replace the words "Full Stop" with the actual punctuation mark "." and "New Paragraph" with " \n\t ".
The code is not giving any error but it is not replacing any string
Actually i see you open the file with r+ which will create a new file if it does not exist, and if it will create it will have no content and then it will raise error.
Better is you check first is the file is empty with
import os
if os.stat("filename.txt").st_size == 0:
# ADD SOME CODE HERE TO ADD CONTENT TO FILE
And then add content
This question already has answers here:
How do I append to a file?
(13 answers)
Closed 1 year ago.
I am trying to get the program to automatically start at the last line of a text file when I run it and make it write on the last line. My current code is as follows:
with open('textfile.txt', 'a+') as tf
last_line = tf.readlines()[-1]
tf.write(linetext + '\n')`
When I run this, it says that the list index is out of range. How do I get this to automatically skip to the last line of a text file and start writing from there?
Use the a flag while opening the file
with open('path/to/file', 'a') as outfile:
outfile.write("This is the new last line\n")