Unterminated string literal python ошибка

Решил запустить скрипт сделал все по инструкции и тут выскакивает такое. Не подскажите как это исправить друзья программисты буду очень благодарен(
Ошибка

C:UsersНатальяAppDataLocalProgramsPythonPython311python.exe C:UsersНатальяPycharmProjectspythonProject1main.py 
  File "C:UsersНатальяPycharmProjectspythonProject1main.py", line 35
    unq_filter_params =["colorbalance=rs=.3","colorbalance=gs=-
                                             ^
SyntaxError: unterminated string literal (detected at line 35)

Process finished with exit code 1

Сам код

import moviepy
from moviepy.editor import *
import random
from pathlib import Path
import string

def create_file_list(folder):
    return [str(f) for f in Path(folder).iterdir()]

def create_image_list(folder):
    image_list=[]
    folder = Path(folder)
    if folder.is_file():
        image = ImageClip(str(folder),duration=1)
        image_list.append(image)
    if folder.is_dir():
        for file in sorted(folder.iterdir(), reverse=True):
            image = ImageClip(str(file),duration=1)
            image_list.append(image)
    return image_list

def filename(folder):
    file_name = ''.join(random.choice(string.ascii_lowercase)
for i in range(5))
    file_name = str(Path(folder).joinpath(file_name + '.mp4'))
    return file_name

#Папка для сохранения видео
result_folder = r'C:UsersНатальяDesktopSAVE'
#Папка с картиками
images = create_image_list(r'C:UsersНатальяDesktopPNG')
#Папка с видео которые будут обработаны
video_ls = create_file_list(r'C:UsersНатальяDesktopVIDEO')
#Фильтрыpip
unq_filter_params =["colorbalance=rs=.3","colorbalance=gs=-
0.20","colorbalance=gs=0.20","colorbalance=bs=-
0.30","colorbalance=bs=0.30","colorbalance=rm=0.30","colorbalanc
e=rm=-0.30","colorbalance=gm=-0.25","colorbalance=bm=-
0.25","colorbalance=rh=-0.15","colorbalance=gh=-
0.20","colorbalance=bh=-0.20"]

Скриншот фрагмента кода удален модератором.

I am trying to use a shutil script I found but it receives SyntaxError: unterminated string literal (detected at line 4). Any assistance would be appreciated to fixing this or new script

import shutil
import os

source = r"C:Users[username]Downloads"
dest1 = r" C:Users[username]DesktopReports14"
dest2 = r" C:Users[username]DesktopReports52"
dest3 = r" C:Users[username]DesktopReports59"

files = os.listdir(source)

for f in files:
   
 if (f.startswith("Log 14")):
        shutil.move(f, dest1)
    elif (f.startswith("Log 54")):
        shutil.move(f, dest2)

asked Dec 9, 2021 at 20:42

Ric 's user avatar

Ric Ric

211 gold badge1 silver badge3 bronze badges

8

Watch out for smart quotes . They need to be double quotes ".

You had smart quotes instead of normal ones. Indenting is also not correct.

Here is the fixed code:

import shutil
import os

source = "C:\Users\[username]\Downloads\"
dest1 = "C:\Users\[username]\Desktop\Reports\14"
dest2 = "C:\Users\[username]\Desktop\Reports\52"
dest3 = "C:\Users\[username]\Desktop\Reports\59"

files = os.listdir(source)

for f in files:
    if f.startswith("Log 14"):
        shutil.move(source + f, dest1)
    elif f.startswith("Log 54"):
        shutil.move(source + f, dest2)

wjandrea's user avatar

wjandrea

27.2k9 gold badges59 silver badges80 bronze badges

answered Dec 9, 2021 at 21:48

norbot's user avatar

norbotnorbot

1876 bronze badges

2

Smart Quotation Marks strike again.

Using BabelStone, one can determine the unicode identification of each character in your code.

The start/ending quotes you’re used to are U0022. However, the end of the URL on dest2 ends with a different character, which is U201D. This is a different character. Easiest way to fix this is to retype out the quotation marks in your IDE.

Input: "”

U+0022 : QUOTATION MARK {double quote}
U+201D : RIGHT DOUBLE QUOTATION MARK {double comma quotation mark}

answered Dec 9, 2021 at 21:43

blackbrandt's user avatar

blackbrandtblackbrandt

1,9871 gold badge15 silver badges32 bronze badges

import os

if os.name == 'nt':    #check if windows 
  a='\'
else:
  a='/'


source = "C:"+a+"Users"+a+"[username]"+a+"Downloads"+a

answered Jul 7, 2022 at 8:21

RITESH 's user avatar

RITESH RITESH

851 silver badge4 bronze badges

3

Genabox
пишешь 3 строчки и чатаешь любые файлы в папках

Сейчас три, потом ещё три, потом ещё три, потом ещё и так далее. Короче, так ты будешь писать в три раза больше, чем если по-нормальному. В этом деле скупой платит дважды.

Закончится всё тем, что ты зайдёшь в тупик, не сможешь продолжать больше писать эту программу, и из-за этого тебе придётся её вообще всю заново писать, с самого начала. И вот там-то ты подумаешь “наверное, надо лучше пакеты сделать, как мне говорили, когда я что-то там думал про себя”.

Genabox
делать пакет для картинки или 3 строчек рут доступа

Это сейчас у тебя три строчки. Но ты смотришь только на момент сейчас, а программа-то живёт ещё и в будущем. Завтра тебе надо будет исправлять баг какой-нибудь в ней, который ты пропустил сегодня и из-за которого завтра просто она вся работать не будет, а ты этот баг не сможешь исправить, потому что исправление бага потребует полного переписывания всей программы. То же самое будет, когда надо будет не баг исправлять, а какую-то фичу добавлять. Ладно, фичу-то можно и не добавлять, а вот если баг не исправлять, который рушит всю работу, то в итоге эта программа вообще будет бесполезна и будет просто из себя представлять кучу потраченного времени и только. Вот из-за этого всего программу надо писать правильно изначально, даже если там одна строчка кода всего лишь.

Genabox
да еще из имени папки и пути делать классоваю переменную

Это слишком сложно для тебя, но я тебе показываю правильный способ.

А вот на счёт sys.path я тебе уже сказал. Все новички делают через sys.path прямо вот точно так же, как вот это ты сейчас делаешь. Как ты думаешь, чем это заканчивается в итоге? Я тебе скажу: нет у них никаких программ в итоге.

Отредактировано py.user.next (Дек. 30, 2022 22:53:51)

We can’t deny that errors are inevitable, and one of them is the syntaxerror: unterminated string literal.

Whether you’re new to coding or even a pro developer, it’s important to understand this error so you can troubleshoot it and bug-free programs.

If you are struggling to fix this error, this article is indeed for you.

In this article, we will explore how to fix the unterminated string literal, a SyntaxError in Python and JavaScript.

The syntaxerror: unterminated string literal occurs when there is an unterminated string literal somewhere in your code. String literals should be enclosed by single (‘) or double (“) quotes.

Here’s an example of code that would cause a SyntaxError, specifically an unterminated string literal, in both Python and JavaScript

Python:

sample_string = "Hi, welcome to Itsourcecode, this a sample of an unterminated string

JavaScript:

let sampleString = "Hi, welcome to Itsourcecode, this a sample of an unterminated string;

As you have noticed in both examples, the string is not properly enclosed by quotes. The closing quote is missing, as a result, it will throw a SyntaxError.

Why does “unterminated string literal” SyntaxError occur?

The syntaxerror: unterminated string literal occurs when you forget to put a closing quotation mark at the end of a string in Python or JavaScript.

It can also happen when you have escaped your string literal incorrectly or if your string literal is split across multiple lines.

Here are the common causes of why this error keeps on bothering you:

👉 One common reason for this error is when the opening and closing quotation marks do not match.

👉 Forgetting to close the string with the correct quotation mark on any line can also trigger this error.

👉 Having special characters within a string, like unescaped quotation marks or newline characters, can interfere with properly ending a string literal.

How to fix the “syntaxerror: unterminated string literal”?

To fix the syntaxerror: unterminated string literal, check if you have to open and close quotes for your string literal, ensure that you have properly escaped your string literal correctly, and avoid splitting your string literal across multiple lines.

Here are the following solutions that can help you to resolve the error.

Solution 1: Add the missing quotation mark

Adding the missing quotation mark fixes the error right away.

For example in Python:

sample_string = "Hi, welcome to Itsourcecode, this a sample of an unterminated string"
print(sample_string)

Output:

Hi, welcome to Itsourcecode, this a sample of an unterminated string

For example in JavaScript:

let sampleString = "Hi, welcome to Itsourcecode, this a sample of an unterminated string";

console.log(sampleString);

Output:

Hi, welcome to Itsourcecode, this a sample of an unterminated string

Solution 2: Split the string across multiple lines using the + operator

If you want to split a string across multiple lines, you can use the + operator to concatenate multiple strings.

For example in Python:

sample_string = ("Hi " ✅
             "welcome to Itsourcecode"
             " this a sample of an unterminated string")
print(sample_string)

Output:

Hi welcome to Itsourcecode this a sample of an unterminated string

For example in JavaScript:

let sampleString = ("Hi, " ✅
                +"welcome to Itsourcecode " 
                + "this a sample of an unterminated string");
console.log(sampleString);

Output:

Hi, welcome to Itsourcecode this a sample of an unterminated string

Solution 3: Use backslashcharacter or escape quotes within the string

If you want to include a quote character within a string, you need to escape it using a backslash ().

For example in Python:

sample_string = ("Hi welcome to "Itsourcecode" this a sample of an unterminated string")✅
print(sample_string)

Output:

Hi welcome to "Itsourcecode" this a sample of an unterminated string

For example in JavaScript:

let sampleString = ("Hi welcome to "Itsourcecode" this a sample of an unterminated string")✅
console.log(sampleString);

Output:

Hi welcome to "Itsourcecode" this a sample of an unterminated string

Solution 4: Use the correct type of quotes

Ensure that you are using the correct type of quotes for your string literals. If you start a string with a single quote (‘), you need to end it with a single quote.

If you start a string with a double quote (“), you need to end it with a double quote.

For example in Python:

sample_string = ('Hi welcome to "Itsourcecode" this a sample of an unterminated string')✅
print(sample_string)

For example in JavaScript:

let sampleString = ('Hi welcome to "Itsourcecode" this a sample of an unterminated string')✅
console.log(sampleString);

Solution 5: Split the string across multiple lines using template literals (JavaScript only)

You can use template literals in JavaScript to split a string across multiple lines.

For example:

let sampleString = `Hi ✅
welcome to Itsourcecode 
this a sample of an unterminated string`;
console.log(sampleString);

Output:

Hi 
welcome to Itsourcecode 
this a sample of an unterminated string

Conclusion

In conclusion, the error message syntaxerror: unterminated string literal occurs when there is an unterminated string literal somewhere in your code. String literals should be enclosed by single (‘) or double (“) quotes.

To fix this error, you have to check if you have to open and close quotes for your string literal, ensure that you have properly escaped your string literal correctly, and avoid splitting your string literal across multiple lines.

This article already discussed what this error is all about and multiple ways to resolve this error.

By executing the solutions above, you can master this SyntaxError with the help of this guide.

You could also check out other SyntaxError articles that may help you in the future if you encounter them.

  • Syntaxerror unexpected reserved word await
  • Uncaught syntaxerror expected expression got
  • Syntaxerror await is only valid in async function

We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊

Seems there are a few problems that crop up when using Python 3.9+

The collections abstract base classes (collections.abc) module was formerly part of the collections module, but I think, was moved in Python 3.8.11. This means several changes are required for python files within the bitbake config directory (see poky/bitbake/lib/bb/)

Even after applying fixes such that collections.abc can import the abstract base class «Mapping» and «MutableMapping» an expansion error will occur with some of the bb expansion variables (SRCREV, FILESPATH, etc.) resulting in an unterminated string literal when attempting to pull or build various recipes.

ERROR: ExpansionError during parsing /drone/src/meta-phosphor/recipes-phosphor/mrw/mrw-native_git.bb
Traceback (most recent call last):
  File "/drone/src/poky/bitbake/lib/bb/data_smart.py", line 587, in DataSmart.getVar(var='FILESPATH', expand=True, noweakdefault=False, parsing=False):
         def getVar(self, var, expand=True, noweakdefault=False, parsing=False):
    >        return self.getVarFlag(var, "_content", expand, noweakdefault, parsing)
     
  File "/drone/src/poky/bitbake/lib/bb/data_smart.py", line 778, in DataSmart.getVarFlag(var='FILESPATH', flag='_content', expand=True, noweakdefault=False, parsing=False, retparser=False):
             if expand or retparser:
    >            parser = self.expandWithRefs(value, cachename)
             if expand:
  File "/drone/src/poky/bitbake/lib/bb/data_smart.py", line 416, in DataSmart.expandWithRefs(s='${@base_set_filespath(["/drone/src/meta-phosphor/recipes-phosphor/mrw/mrw-1.0+git${SRCPV}", "/drone/src/meta-phosphor/recipes-phosphor/mrw/mrw", "/drone/src/meta-phosphor/recipes-phosphor/mrw/files"], d)}', varname='FILESPATH'):
                     tb = sys.exc_info()[2]
    >                raise ExpansionError(varname, s, exc).with_traceback(tb) from exc
     
  File "/drone/src/poky/bitbake/lib/bb/data_smart.py", line 403, in DataSmart.expandWithRefs(s='${@base_set_filespath(["/drone/src/meta-phosphor/recipes-phosphor/mrw/mrw-1.0+git${SRCPV}", "/drone/src/meta-phosphor/recipes-phosphor/mrw/mrw", "/drone/src/meta-phosphor/recipes-phosphor/mrw/files"], d)}', varname='FILESPATH'):
                     try:
    >                    s = __expand_python_regexp__.sub(varparse.python_sub, s)
                     except SyntaxError as e:
  File "/drone/src/poky/bitbake/lib/bb/data_smart.py", line 114, in VariableParse.python_sub(match=<re.Match object; span=(0, 89), match='${@base_set_filespath(["/drone/src/meta-phosphor/>):
                     varname = '<expansion>'
    >            codeobj = compile(code.strip(), varname, "eval")

bb.data_smart.ExpansionError: Failure expanding variable FILESPATH, expression was ${@base_set_filespath(["/drone/src/meta-phosphor/recipes-phosphor/mrw/mrw-1.0+git${SRCPV}", "/drone/src/meta-phosphor/recipes-phosphor/mrw/mrw", "/drone/src/meta-phosphor/recipes-phosphor/mrw/files"], d)} which triggered exception SyntaxError: unterminated string literal (detected at line 1) (Var <FILESPATH>, line 1)

Понравилась статья? Поделить с друзьями:
  • Unsupported command 7 zip ошибка
  • Unsupported alpine ошибка
  • Unrouteable address ошибка почты
  • Unresolved reference python ошибка
  • Unrecognized upnp response ошибка upnp wizard